Let's say I call QtConcurrent::run()
which runs a function in a worker thread, and in that function I dynamically allocate several QObjects (for later use). Since they were created in the worker thread, their thread affinity should be that of the worker thread. However, once the worker thread terminates, the QObject thread affinity should no longer be valid.
The question: Does Qt automatically move the QObjects into the parent thread, or are we responsible in moving them to a valid thread before the worker thread terminates?
No, Qt doesn't automatically move
QObject
into the parent thread.This behavior doesn't explicitly documented, so I've done a small investigation of the Qt framework source code, master branch.
QThread
starts inQThreadPrivate::start
:QThread::terminate()
implementation:In both cases thread finalization is done in
QThreadPrivate::finish
:It posts
QEvent::DeferredDelete
event to cleanupQObject::deleteLater
, than TLS data cleaned up withQThreadStorageData::finish(tls_data)
andeventDispatcher
deleted. After thatQObject
will receive no events from this thread, butQObject
's thread affinity stays the same. It's interesting to see implementation ofvoid QObject::moveToThread(QThread *targetThread)
to understand how thread affinity changes.Implementation of
void QThreadPrivate::finish(void *arg, bool lockAnyway)
makes clear thatQObject
's thread affinity is not changed byQThread
.Although this is an old question, I recently asked the same question, and just answered it using QT 4.8 and some testing.
AFAIK you cannot create objects with a parent from a QtConcurrent::run function. I have tried the following two ways. Let me define a code block then we will explore the behavior by selecting POINTER_TO_THREAD.
Some psuedo code will show you my test
Ignoring potential scoping issues...
If
POINTER_TO_THREAD
is set tothis
, then you will get an error becausethis
will resolve to a pointer to theanInstance
object which lives in the main thread, not the thread QtConcurrent has dispatched for it. You will see something like...Cannot create children for a parent in another thread. Parent: anInstance, parents thread: QThread(xyz), currentThread(abc)
If
POINTER_TO_THREAD
is set toQObject::thread()
, then you will get an error because because it will resolve to the QThread object in whichanInstance
lives, and not the thread QtConcurrent has dispatched for it. You will see something like...Cannot create children for a parent in another thread. Parent: QThread(xyz), parents thread: QThread(xyz), currentThread(abc)
Hope my testing is of use to someone else. If anyone knows a way to get a pointer to the QThread which QtConcurrent runs the method in, I would be interested to hear it!
I am not sure if Qt automatically change the thread affinity. But even if it does, the only reasonable thread to move to is the main thread. I would push them at the end of the threaded function myself.
Now this only matters if the objects make use of event process like send and receive signals.
The worker thread does NOT terminate after your function call. The whole point of using
QtConcurrent::run
is executing a large number of small tasks on the global thread pool (or some providedQThreadPool
) while re-using threads to avoid the overhead of creating and destroying threads for each one of these small tasks. In addition to distributing computation across all available cores.You can try looking at the source code for Qt to see how
QtConcurrent::run
is implemented. You will see that it ends up callingRunFunctionTaskBase::start
, which essentially callsQThreadPool::start
with aQRunnable
that calls the function that was passed initially toQtConcurrent::run
.Now the point that I want to get to is that,
QThreadPool::start
is implemented by adding theQRunnable
to a queue, and then trying to wake up one of the threads from the thread pool (which are waiting for a newQRunnable
to be added to the queue). The thing to note here, is that threads from the thread pool are not running an event loop (they are not designed to act this way), they are there just to executeQRunnable
s in the queue and nothing more (they are implemented this way for performance reasons obviously).This means that, the moment you are creating a
QObject
in a function executed inQtConcurrent::run
, you are just creating aQObject
that lives in a thread with no event-loop, from the docs, restrictions include:TL;DR:
QtConcurrent::run
runs functions in threads from the globalQThreadPool
(or a provided one). Those threads do not run an event loop, They just wait forQRunnable
s to run. So, aQObject
living in a thread from these threads doesn't get any events delivered.In the documentation, They have put using
QThread
(possibly, with an event loop and a worker object) and usingQtConcurrent::run
as two separate multi-threading technologies. They are not meant to be mixed together. So, no worker objects in thread pools, this is just asking for trouble.I think that after looking at things this way, The answer is obvious that Qt does NOT move
QObject
s into any thread automatically. The documentation has warned about using aQObject
in aQThread
without an event loop, and that's it.You are free to move them to whatever thread you like. But please keep in mind that
moveToThread()
can sometimes cause problems. For example, if moving your worker object involves moving aQTimer
:Conclusion: I think that you should consider using your own
QThread
that runs its event loop, and create your workerQObject
s there instead of usingQtConcurrent
. This way is far better than movingQObject
s around, and can avoid many errors that can arise from using your current approach. Have a look at the comparison table of multi-threading technologies in Qt and choose the technology that best suits your use case. Only useQtConcurrent
if you want to just execute a one-call function and get its return value. If you want permanent interaction with the thread, you should switch to using your ownQThread
with workerQObject
s.Although the Qt docs don't appear to specify the behaviour you could find out by keeping track of what
QObject::thread()
returns before and after the thread finishes.QThread
is not documented to automatically move anyQObject
s when it finishes, so I think we can already conclude that it does no such thing. Such behavior would be very surprising, and at odds with the rest of the API.Just for completeness, I tested with Qt 5.6:
Recall that a
QThread
is not a thread, it manages a thread.When a
QThread
finishes, it continues to exist, and the objects that live in it continue to live in it, but they no longer process events. TheQThread
can be restarted (not recommended), at which point event processing will resume (so the sameQThread
could then be managing a different thread).When a
QThread
is destroyed, the objects that lived in it cease to have any thread affinity. The documentation doesn't guarantee this, and in fact says "You must ensure that all objects created in a thread are deleted before you delete theQThread
."The
QThread
does not terminate in this scenario. When a task spawned byQtConcurrent::run
finishes, theQThread
it was running in is returned to theQThreadPool
and may be reused by a subsequent call toQtConcurrent::run
, andQObject
s living in thatQThread
continue to live there.You might want to manually move an object out of a
QThread
before it is returned to theQThreadPool
, or just don't useQtConcurrent::run
. Having aQtConcurrent::run
task constructQObject
s which outlive the task is a questionable design, tasks should be self-contained. As noted by @Mike, theQThread
s used byQtConcurrent::run
do not have event loops.