Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
868 views
in Technique[技术] by (71.8m points)

multithreading - emit Qt signal from non Qt Thread or ouside Qt main event loop with at 4.5

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...