[SOLVED] Qt: Main thread signal + worker thread slot.
-
Say I wanted to have a worker thread that has slots for signals emmited from the main application thread.
How would the "::run()" method of that worker thread look? obviously I need some kind of loop or the thread will terminate immediately. I want it to stick around so it can process the incoming slots. How would that loop look like? Something equivalent to sleep and pump messages? pump how?
Do I need to "MoveToThread()" all the objects that'll pass to the thread's slots so that the processing of the slot is processed in the context of the worker thread?
Thank you.
-
Did some more digging.
The default implementation of QThread::run calls "exec" which is the message loop. So no extra work needed there. In the constructor of my QThread I add this:
@this->start();
QObject::moveToThread(this);@As a result, my thread starts upon construction, and all signals outside the thread aimed at thread slots are executed in the context of my thread.
-
[quote author="ronM71" date="1311713565"]
@this->start();
QObject::moveToThread(this);@
[/quote]
It's generally discouraged to call
@
moveToThread(this);
@Have a look at this blog post: http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/
More on this topic here:
http://blog.exys.org/entries/2010/QThread_affinity.htmlSo you don't need to subclass QThread at all. You can simply use "moveToThread" to push any QObject to another thread, and the slots of that object will be executed by that thread. A nice example can be found here: http://chaos.troll.no/~bhughes/producerconsumer2.tar.gz
-
[quote author="LinusA" date="1311714232"]
[quote author="ronM71" date="1311713565"]
@this->start();
QObject::moveToThread(this);@
[/quote]
It's generally discouraged to call
@
moveToThread(this);
@Have a look at this blog post: http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/
More on this topic here:
http://blog.exys.org/entries/2010/QThread_affinity.html
That link above is a dead end!
[/quote] -
Try these links:
"You're doing it wrong":http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/
"best practise for QThread":http://qt-project.org/wiki/QThreads_general_usage
"doc note in QThread reference":http://qt-project.org/doc/qt-4.8/QThread.html#notes