In general, as a personal opinion, I would not mix blocking code (like that QWaitCondition
) with event loop even in a thread, unless you know it will not block for long. For GUI thread, I'd say "long" is more than 100ms (longer than that and user experience starts to suffer even in traditional desktop apps), but for other threads it may be much longer, depending on how long it's ok block all events and signals that thread needs to handle.
With multiple threads, it's generally better to use automatic or explicitly queued connections for signals. Direct connection will execute in the thread where signal is emitted, and if receiving object lives in another thread, then the slot (and as a consequence, everything releated in the class) needs to be made thread safe. Much simpler and safer to not do it that way, one less thing to keep track of.
If you write code now in one thread, but want to prepare to move it to other thread later, then better make the connection queued. That way the behaviour will be largely same already with single thread, emit
will return immediately, and you get no surprises later.
If you want to write code that blocks for undetermined or otherwise too long time in any thread, it's better to subclass QThread
, override QThread::run()
and never call exec()
in it. Then you can use QMutex and QWaitCondition in your own loop, or use some other "traditional" inter-thread communication method. You can still emit signals from the thread, but connections should be queued to avoid threading problems. Also remember that any slots you add to the QThread should execute in the thread where QThread object lives, not the thread where run()
method is executing. This is actually quite convenient pattern, you can "hide" all actual thread interaction code in the slots of your QThread subclass (remember, they do not execute in the thread where run()
runs), as long as you take care not lock any QMutex
used in these for too long time.