I have a multithreaded application written in C++ with Qt. Currently, my application works by having a QThread
instance (I have NOT subclassed QThread
) which uses the default run()
implementation that just calls QThread
's exec()
method, which provides an event dispatch loop.
I call moveToThread
on certain QObject
subclasses which actually perform the work I want done in a separate thread. I tell these objects to do work using Qt's signals/slots mechanism. I stop the thread gracefully by informing my worker objects to stop their work, and then calling quit()
and wait()
on my thread. This all works very nicely.
However, I now want to implement the following scenario:
- The user clicks e.g. the "X" button on my application, because they want to close it.
- I don't want any new work to be started, so I pause the event dispatch thread. If the current event being dispatched continues running, that's fine.
- I prompt the user, allowing them to either a) discard all remaining jobs and exit (using
quit() and
wait()` - this already works), or b) don't exit the application, but instead continue working (resume the thread).
My problem is that QThread
doesn't seem to have a pause()
method. I've seen various examples online which add one (like the answers to this question). The problem is that these examples depend on having a custom run()
implementation, and implementing pause there. Since I'm relying on QThread
's event dispatch loop, these solutions won't work. I've considered doing something like reimplementing exec()
or creating my own subclass of QAbstractEventDispatcher
, but these solutions seem like a whole lot of work to get simple pause / resume functionality.
What's the easiest way to pause QThread's event dispatch loop (preventing it from dispatching any new events, but letting the current event continue)?