Trevor
Trevor

Reputation: 31

Why does QThread only print one of two thread calls?

from PySide.QtCore import *
from PySide.QtGui import *
import time as t


class WorkerThread(QThread):
    def _init_(self, mw):
    super(WorkerThread, self)._init_(mw)
    self.gameName = ""

def setGameName(self, currGameName):
    self.gameName = currGameName

def run(self):
    print self.gameName

class GG(object):
workerThread = WorkerThread()
def startThread(self,stringer):
    self.workerThread.setGameName(stringer)
    self.workerThread.start()

harro = GG()
harro.startThread("hello")
harro.startThread("hi")
t.sleep(60)

This only prints "hi" and not "hello". Why does it not print both? How would I change it so that it prints both?

Upvotes: 1

Views: 78

Answers (2)

Kif
Kif

Reputation: 265

The example is quite small, in that the threads only do one thing (print a string), then exit. If you actually want to start two threads in parallel, you could modify your GG class to keep track of more than one thread object.

class WorkerThread(QThread):
    def _init_(self, mw):
        super(WorkerThread, self)._init_(mw)
        self.gameName = ""

    def setGameName(self, currGameName):
        self.gameName = currGameName

    def run(self):
        print self.gameName

class GG(object):
     workerThreads = []

     def startThread(self,stringer):
        self.workerThreads.append(WorkerThread())
        self.workerThreads[-1].setGameName(stringer)
        self.workerThreads[-1].start()

harro = GG()
harro.startThread("hello")
harro.startThread("hi")

Upvotes: 0

Mel
Mel

Reputation: 6075

The second call to startThread cancels the first one. The thread don't have time to print "hello" that you call it again asking to print "hi". You can call QThread.wait() just after QThread.start() to wait for the thread to finish.

A working example (also, with correct identation):

class WorkerThread(QThread):
    def _init_(self, mw):
        super(WorkerThread, self)._init_(mw)
        self.gameName = ""

    def setGameName(self, currGameName):
        self.gameName = currGameName

    def run(self):
        print self.gameName

class GG(object):
     workerThread = WorkerThread()

     def startThread(self,stringer):
        self.workerThread.setGameName(stringer)
        self.workerThread.start()
        self.workerThread.wait()

harro = GG()
harro.startThread("hello")
harro.startThread("hi")

This example would freeze a user interface while a thread is running. So for more complex tasks, you should use the signals and slots mechanism.

Upvotes: 4

Related Questions