# Alternative to using sleep() to avoid a race condition in PyQt

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()

-

## 1 Answer

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.

-