Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have a situation where I would like to use a single QThread to run two (or more) separate methods at different times. For example, I would like the QThread to run play() sometimes, and when I am done playing, I want to disconnect the QThread.started() signal from this method so that I may connect it somewhere else. In essence I would like the QThread to act as a container for anything I would like to run in parallel with the main process.

I have run into the problem where starting the QThread and then immediately disconnecting the started() signal it causes strange behavior at runtime. Before I discovered what 'race condition' meant (or really understanding much about multithreading), I had the sneaking suspicion that the thread wasn't fully started before being disconnected. To overcome this, I added a 5 ms sleep in between the start() and disconnect() calls and it works like a charm. It works like a charm but it isn't The Right Way.

How can I implement this functionality with one QThread without making the call to sleep()?

Thanks!

Code Snippet:

def play(self):

    self.stateLabel.setText("Status: Playback initated ...")

    self.myThread.started.connect(self.mouseRecorder.play)
    self.myThread.start()
    time.sleep(.005)  #This is the line I'd like to eliminate

    self.myThread.started.disconnect()

def record(self):

    self.stateLabel.setText("Status: Recording ...")  

    self.myThread.started.connect(self.mouseRecorder.record)
    self.myThread.start()
    time.sleep(.005) #This is the line I'd like to eliminate        

    self.myThread.started.disconnect()
share|improve this question

1 Answer 1

up vote 3 down vote accepted

Use a Queue, python has a threadsafe Queue class.

Push the function you want to run on the background thread onto the queue.

Have the thread wait on the queue executing functions as they are put into it.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.