[Interest] Emitting signal from QThread::run()

Bo Thorsen bo at vikingsoft.eu
Mon Feb 29 13:14:46 CET 2016


Den 27-02-2016 kl. 07:15 skrev Syam:
>
> Hello,
>
> Inspired from the recent discussions on QThread, I have the following
> question.
> I have:
>
> class MyThread : public QThread
> {
>     Q_OBJECT
>      //the constructor and other stuff
>
> signals:
>       void mySignal();
>
> protected:
>    virtual void run()
>    {
>       while(true)
>       {
>          //do something
>          if(some_condition) emit mySignal();
>       }
>    }
> };
>
>
> void MainWindow::someFunction()
> {
>     MyThread *thread = new MyThread;
>     connect(thread, SIGNAL(mySignal()), this, SLOT(myGuiSlot()),
> Qt::QueuedConnection);
>     thread->start();
> }
>
>
> //////////////////
>
> Will the above code work fine? In myGuiSlot() I am typically
> manipulating some widgets - setting the text of a QLabel etc.

Don't ever do this. I don't subscribe to the idea that you should never 
subclass QThread yourself, but I think it's a very bad idea to subclass 
and use signals and slots.

The reason is the discussion that followed in this thread - it's so hard 
to understand precisely what happens with the connected signals and slots.

I usually tell people that QThread is a bridge between the creating and 
the created thread. It's not actually, but conceptually it helps them to 
realize that they should not assume they can understand the qobject 
thread affinity inside the object itself.

If you use signals and slots in a thread object, you do this:

QThread* thread = new QThread;
MyObject* object = new MyObject;
object->moveToThread(thread);
thread->start();

If you don't and only do calculation, or use a queue or something to 
handle the communication with hardware, etc, then you can subclass 
QThread and do stuff in run(). (This part is where I disagree with the 
"you're doing it wrong" crowd.) This is safe because without signals and 
slots in there you don't use the thread affinity and you don't have a 
local event loop.

Guys, this is only hard if you insist on doing something that 
experienced people say you should stay away from. The OP thought the 
MyObject should create it's own thread. No, that's wrong. Accept it and 
move on. Or create a wrapper object around it if you must encapsulate it.

Bo Thorsen,
Director, Viking Software.

-- 
Viking Software
Qt and C++ developers for hire
http://www.vikingsoft.eu



More information about the Interest mailing list