我在我的应用程序中使用了一些 QThread
。
我的对象“生活”在不同的线程中(它们的所有者线程,因为 Qt 意味着它是不同的)并使用带有排队连接的信号/插槽进行通信。
现在,我遇到了这个问题:
- 对象“A”存在于
QThread
“A” - 对象“B”存在于
QThread
“B” - Gui 住在“主线程”
然后:
- 对象“A”从它自己的线程“A”调用“B”实例上的方法
B::foo
- 此
B::foo
方法共享的资源使用互斥锁进行保护,在这里从线程“A”执行B::foo
没有问题< - 在
B::foo
方法中,对象“B”发出信号barSignal
我对他的配置有一些疑问:
从不是“B”所有者的
QThread
的线程发出对象“B”的信号是否安全?在“Qt 主线程”中的 GUI 对象中使用
Qt::AutoConnection
接收此信号是否安全?使用
Qt::AutoConnection
在对象“C”中接收此信号是否安全,该对象“C”位于它自己的QThread
“C”中?
我的测试倾向于对所有内容说"is"。
通过阅读Qt的emit
代码,好像没问题。
但它在 Qt 文档中没有找到任何关于“从不是发射器所有者线程的线程发出信号”的信息。
最佳答案
从其他线程发出信号是安全的,如果您使用自动或排队连接。在接收 QObject
没有关联的线程中发出信号的情况下,Auto 被推断为排队。直接连接不是线程安全的。
有一个"Signals and Slots Across Threads"文档中处理向不同线程中的对象发出信号的部分。
Queued Connection - The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
还有
The connection type can be specified by passing an additional argument to connect(). Be aware that using direct connections when the sender and receiver live in different threads is unsafe if an event loop is running in the receiver's thread, for the same reason that calling any function on an object living in another thread is unsafe.
QObject::connect() itself is thread-safe.
关于multithreading - 可以从另一个 QThread 安全地发出 Qt 信号吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36935868/