从非Qt线程或ouside Qt主事件循环发出Qt信号,为4.5

时间:2022-12-06 10:59:15

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.

我从非Qt线程调用emit signal1()。非Qt线程我的意思不是来自GUI事件循环而不是来自任何QThread run()方法或任何QThread自己的事件循环。

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

它只是一个pthread(pthread_create()),它调用一个发出信号的QObject方法。

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.

我的pthread的“run”方法,它有一个指向MyObject实例的指针(在主Qt GUI线程上下文中创建的实例而不是pthread)调用emitBunchOfSignals()方法。

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

在Qt 4.5之前,这是令人讨厌的。现在,Qt 4.5会处理这个吗?它是否调用qApp-> PostEvent()或其他东西,以便在Qt GUI线程内发出信号(因此也就是插槽)?

thanks

谢谢

1 个解决方案

#1


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:

您需要确保使用与线程的排队连接,因为Qt无法自动检测哪个对象属于哪个线程(“线程关联”是文档中使用的术语)。您在连接时执行此操作:

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

这将导致信号被置于目标的事件循环上,并且当其线程正在运行时(即其事件循环)调用该槽。

#1


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:

您需要确保使用与线程的排队连接,因为Qt无法自动检测哪个对象属于哪个线程(“线程关联”是文档中使用的术语)。您在连接时执行此操作:

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

这将导致信号被置于目标的事件循环上,并且当其线程正在运行时(即其事件循环)调用该槽。