12

I'm calling a emit signal1() from a non Qt thread. By non Qt thread I mean not from the GUI Event Loop and not from any QThread run() method or any QThread own event loop.

It is simply a pthread (pthread_create()) that calls a method of a QObject which emits signals.

ex:

MyQbject: public QObject
{
...
void emitBunchOfSignals()
{
 emit signal1();
 emit signal2();
 ...
}
...
}

the "run" method of my pthread which has a pointer to a MyObject instance (instance that was created within the main Qt GUI thread context NOT the pthread) calls the emitBunchOfSignals() methods.

Before Qt 4.5 that was nasty. Now, does Qt 4.5 handle this ? Does it call qApp->PostEvent() or something so the signal is emitted within the Qt GUI Thread (and thus the slot as well) ?

thanks

masoud
  • 55,379
  • 16
  • 141
  • 208
Nicolas Robert
  • 231
  • 2
  • 6
  • When you call connect, you might explicitly set the type to queued connection. – Kaleb Pederson Jan 15 '10 at 15:46
  • In the time it took you to write down this question you could have just opened the code and look for yourself. – shoosh Jan 15 '10 at 16:00
  • It does not seem straight forward as it used to crash with Qt 3.xx. I'm familiar with the connect option (directconnection queuedconnection etc) but I thought it worked only between QTreads or between a QThread and the main event loop. Why it used to crash with Qt 3.xx at least was not straight forward to understand by looking at the code. Am I crazy ? – Nicolas Robert Jan 15 '10 at 16:10
  • @Nicolas - Some of the threading code and necessary background make it quite difficult to easily understand what's going on. There's a lot to navigate through, like thread pools, moc, and others. – Kaleb Pederson Jan 15 '10 at 18:36

1 Answers1

9

What you need to make sure is that you use a queued connection to a from threads, as Qt cannot autmatically sense which object that belong to which thread ("thread affinity" is the term used in the documentation). You do this when connecting:

connect(src, SIGNAL(signal-signature), dest, SLOT(slot-signature), Qt::QueuedConnection);

That will result in the signal being put on the event loop of the destination, and the slot being called when its thread is running (i.e. its event loop).

e8johan
  • 2,899
  • 17
  • 20
  • 3
    thanks a lot. To make sure I understand what you mean: Since my emitting QObject does not belong to a QThread nor the main Qt GUI Thread (it belongs to my Corba thread actually), Qt cannot sense the thread affinity. Thus I have to force the connection to QueuedConnection as AutomaticConnection won't work in this specific case. However when the emitting QObject belongs to a QThread, Qt can sense the thread affinity and a automaticConnection will do the necessary post to the receiver QObject thread's Event loop. – Nicolas Robert Jan 18 '10 at 12:45