[Interest] Is it OK to emit from different thread?

Jérôme Godbout godboutj at amotus.ca
Fri Nov 30 22:34:45 CET 2018


While I agree with your point, it’s easy to shoot yourself in the foot as soon as one add a slots into that QThread inherited class (can see the kdab recommendation on the subject point #5: https://www.kdab.com/nailing-13-signal-slot-mistakes-clazy-1-3/ ). Your green developer will be tempted to add a slots into this object if they feel they need a slots and there the fun will be over. Having to specify your connect() not auto is very rare.

From: Konstantin Shegunov <kshegunov at gmail.com>
Sent: November 30, 2018 4:05 PM
To: Jérôme Godbout <godboutj at amotus.ca>
Cc: Konstantin Tokarev <annulen at yandex.ru>; Alexander Dyagilev <alervdvcw at gmail.com>; Interests Qt <interest at qt-project.org>
Subject: Re: [Interest] Is it OK to emit from different thread?

On Fri, Nov 30, 2018 at 10:49 PM Jérôme Godbout <godboutj at amotus.ca<mailto:godboutj at amotus.ca>> wrote:
If you use automatic connection when doing this you will run into troubles and my be surprise by the signals sent from the thread execution (they will act like if they were sent from the Qthread creator and not the actual executing qthread and this is bad.

No they will not. They will act just like they've been sent from the thread that does the emit.
If you see some code where people tell they have to specify the queued connection manually, it smell like a QThread have been inherited to inline the run and they "fixed" the problem. I do a lot of Threading inside my application and I never inherit it and never had any problems with my thread either.

You don't need to use Qt::QueuedConnection when inheriting QThread and emitting from QThread::run, and I've done that aplenty. There's no problem with it, as long as you realize the QThread object is in the thread that created it - i.e. its internal data is not owned by QThread::run. With auto connection Qt will do the right thing and queue the slot call if the receiving thread is different from QThread::run (which it really almost always is) and to be really explicit this determination whether to queue, or to call directly is done at the time of emit (more concretely in QMetaObject::activate and its friends) and not at time of making the connections.

Running imperative code in a subclassed thread is perfectly fine. Not every thread needs an event loop.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20181130/137a4a96/attachment.html>


More information about the Interest mailing list