Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: Correct way to post events to a QThread?

In my Qt application, I have a main thread and a worker thread. The worker thread subclasses QThread and processes events via customEvent. Is this the correct way for the main thread to send events to be processed by the worker thread?

QThread* myWorkerThread = // ...

QApplication::instance()->postEvent (myWorkerThread, new MyWorkRequestEvent(/* ... */);

If I read the documentation correctly, it states that events are processed on the thread of the object that own the event recipient. Since QThread was created by the main thread, it is owned by the main thread -- so would this event be processed by the main thread (which would be counter-intuitive, and in my case would be wrong)?

like image 571
Tony the Pony Avatar asked Jun 01 '11 22:06

Tony the Pony


1 Answers

Your understanding is correct and is indeed very unintuitive :)

A lot of the trouble comes from the documentation for QThread that suggests subclassing QThread. Although Qthread has its own event loop, only events and signals for QObjects created in the run() method (created in that thread) will be processed in the QThread event loop.

It is much better to encapsulate your thread logic in a QObject subclass and then move that object to an instance of a plain QThread. You can then communicate with that QObject using signals (which will be correctly queued across thread boundaries) or custom events.

There are some links in this similar question that should help.

like image 101
Arnold Spence Avatar answered Nov 12 '22 05:11

Arnold Spence