Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling QThread.exec() method is necessary in QThread?

I am not calling exec() in my code, but the timer and QUdpSocket is working fine. Is exec() used to wait for an event to continue?

UPDATE: the timer was working, because I had not called moveToThread(this) on the QThread, which meant the QThread was actually still part of the main thread. As for QUdpSocket well I using the polling functions. So it did not need to work with signals.

TIP: if you need to do init stuff, that requires an event loop in your QThread, you can delay calling moveToThread until you don't need the signals anymore, that is practical when the program is loading. You also don't need to call it in the constructor (you could call it inside run() for example), just copy the this QThread pointer to a variable and make the call later/elsewhere using the pointer.

like image 666
yan bellavance Avatar asked Feb 26 '10 05:02

yan bellavance


1 Answers

Your timer and socket are probably using the main event loop that is started when you call QCoreApplication::exec(). Although I'm sure there's a good reason to run an event loop within a thread, I can't come up with one.

The QThread documentation states:

Each QThread can have its own event loop. You can start the event loop by calling exec(); you can stop it by calling exit() or quit(). Having an event loop in a thread makes it possible to connect signals from other threads to slots in this thread, using a mechanism called queued connections. It also makes it possible to use classes that require the event loop, such as QTimer and QTcpSocket, in the thread. Note, however, that it is not possible to use any widget classes in the thread.

Without an event loop, it's possible to emit signals which are processed by the GUI thread, or a different thread containing an event loop. This implies that a thread must have an event loop in order for its slots to be effectual. Per the documentation above, some classes, like QTimer, require a running event loop for which you must call QThread::exec(). Other classes, like QTCPSocket have capabilities to run with with or without an event loop, depending on the functions used. The documentation for the classes should indicate what, if any, requirements they have.

like image 180
Kaleb Pederson Avatar answered Sep 20 '22 06:09

Kaleb Pederson