View Full Version : moveToThread() Problem

12th June 2009, 17:17

Im having some problems related to thread affinity.

Basically I create some worker threads from my main thread as follows:


I perform the moveToThread() to ensure that objects instantiated inside the threads run() method are in the new thread and not the main thread context (this is a problem if i dont moveToThread()).

This all works perfectly, until I shut the threads down. When this happens I get some very strange errors (segfaults mostly). I think this is because when the threads shut down, the thread object is now living in a non-existent thread.

Please could someone give me some idea of how to avoid this problem? My requirements are simply that everything in the threads run() function are created/executed under that threads context as opposed to the parent thread. moveToThread() achieves this, but introduces problems when the thread closes itself, because once closed the thread its supposed to live in a thread which no longer exists.

The threads run() method is as followed.

void NThread::run()
qDebug()<<"[Starting Thread] : "<<QThread::currentThreadId();


// enter event loop

Many thanks

15th June 2009, 19:33
Objects created inside run() are always associated with the new thread, you don't need to move the thread object itself to the new thread for that.

If your objects crash after the thread ends then there is something wrong with them. If you return from exec(), events are not handled anymore so the thread object can't crash because none of its events will be executed as it is not associated with any event loop. And by the way, you can always push the thread object back to the main thread after exec() returns but I doubt it will solve your problem. It's probably elsewhere.