[Qt-interest] Queued/DirectConnections for signals across threads

Andre Somers andre at familiesomers.nl
Mon Dec 14 09:46:50 CET 2009


Hi,

Preet wrote:
> Object A is reading in a file line by line until eof(). I want to be 
> able to 'pause' this process briefly and resume it again with a 
> control flag. The object also does other stuff which requires it to 
> have an event loop.
If you need an eventloop to function properly, then give it the chance 
to do it's job and dont't run in an infinate loop. Instead, you could 
use a QTimer with interval 0, a single shot QTimer at the end of each 
iteration, or a QMetaObject::invokeMethod with a Qt::QueuedConnection at 
the end of each iteration to trigger the next iteration. This way, you 
keep your eventloop able to actually process the events you need.
>
> I'm not understanding the difference between how queued connections 
> and direct connections behave in this context. The Qt docs state:
>
> Qt::DirectConnection 	1 	When emitted, the signal is immediately 
> delivered to the slot.
> Qt::QueuedConnection 	2 	When emitted, the signal is queued until the 
> event loop is able to deliver it to the slot.
>
>
> So shouldn't a directly connected signal just force Object A to jump 
> from whatever line it is executing to the beginning of the respective 
> slot?
No!
A direct connection will cause execution of the code in the slot in the 
thread context of the calling thread! That you have created your object 
A in thread 1 does not mean that thread 2 can not execute code on it. 
So, if you use a direct connection, you have two execution paths 
simultaniously in a single object A. How that works out, very much 
depends on the details of your implementation. However, if it is just 
setting a pause flag you check regulary from a loop in another thread, I 
guess that should Work Just Fine (TM), especially if it is not really 
critical that execution stops immediately.

>
> Here's Object A reading a file (no Qt, just a simple while loop)
>
>
> void ObjectA::RunFileInput
> while(1)
> {
> _axis->_lockStateData.lock();
> if (!(_axis->_fileInputRunning)) { break; }
> _axis->_lockStateData.unlock();
> _axis->playbackFile >> fileRow.data_;
> if (_axis->playbackFile.eof()) { break; }
> usleep(50*1000);
You realize that this will block this thread? Don't use a neverending 
loop (BTW, we have a "forever" keyword for that in Qt, more readable 
than while(1) IMHO) if you need an eventloop to work, especially if that 
loop can really take a long time like in your case...

André



More information about the Qt-interest-old mailing list