July 26, 2011

ronM71 ronM71
Lab Rat
225 posts

[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.

  1. 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?
  1. 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.

5 replies

July 26, 2011

ronM71 ronM71
Lab Rat
225 posts

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:

  1. this->start();
  2. 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.

July 26, 2011

LinusA LinusA
Lab Rat
62 posts

ronM71 wrote:

  1. this->start();
  2. QObject::moveToThread(this);


It’s generally discouraged to call
  1. 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

So 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

 Signature 

Using Qt 4.7.3 and OpenCV 2.2 on Windows XP/7 32bit with VS 2008

July 26, 2011

ronM71 ronM71
Lab Rat
225 posts

Thanks for the tip. I’ll adopt.

December 3, 2012

astodolski astodolski
Ant Farmer
106 posts

LinusA wrote:

ronM71 wrote:

  1. this->start();
  2. QObject::moveToThread(this);


It’s generally discouraged to call
  1. 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!

December 3, 2012

KA51O KA51O
Robot Herder
397 posts

Try these links: You’re doing it wrong [blog.qt.digia.com] best practise for QThread [qt-project.org] doc note in QThread reference [qt-project.org]

 
  ‹‹ Slots not being called in shared library (Mac)      Qt Solutions archive, is it safe to use them for new projects, are there replacement Classes? ››

You must log in to post a reply. Not a member yet? Register here!