How to pause and resume threads in pyqt?

Hi, I have a pyqt app that I get frames from a camera (not webcam it has its own library) and process frames then put frames into a big numpy array to make a big image, so I have a worker thread that does all processes and shows live frames and thumbnail and ROIs in gui using signals and slots, inside run function of worker thread I have multiple while loops that are needed for my processes, how can I add a pause and resume functionality to it?
also I added another worker thread to my app to handle saving and converting operations of big image but when I click those buttons GUI gets stuck for a second then it comes responding is there anything I should do to make it realtime and not stuck for a second or its how it should work?

Hi @SinPool welcome the forum.

For the pause/resume functionality you need to add a flag onto the thread, which can be set/unset from outside. In the __init__ of your thread class, add a flag, e.g. self.is_paused = False.

In the main loop, check for the state of this flag, and perform an loop while waiting. You will want to add a time.sleep() in there to avoid hogging the cpu doing nothing, set the time depending on how quickly you need it to start up when unpaused.

while self.is_paused:
     time.sleep(0.1)

To pause the thread from outside, you just need to set the is_paused flag to True. You can either do this directly, or using methods, e.g.

def pause(self):
    self.is_paused = True

def resume(self):
    self.is_paused = False

Then on your thread object you can call

thread.pause()
# ...
thread.resume()

To pause and restart it.

1 Like