c++ - Qt 的事件循环线程是安全的还是原子的?处理 `QueuedConnection` 时如何同步?

标签 c++ multithreading qt qt-events queued-connection

假设 2 个 QThread 以下列关系运行:

connect(&Object1OfThread1, &Object1::Signal, 
        &Object2OfThread2, &Object2::Slot, Qt::QueuedConnection);

因此,当一个线程的对象发出信号时,会调用另一个线程的槽。正如在 Qt signals (QueuedConnection and DirectConnection) 中讨论的那样,由于 Qt::QueuedConnectionSignal() 被发布/附加到 Thread2 的事件循环中。轮到它时,将调用 Slot()

问题:事件循环本身是线程安全的吗?
即。如果线程 1 和线程 3 同时向线程 2 的事件循环发送信号会怎样。

最佳答案

this comment中提到的文章, 表示事件队列受互斥体保护。

How Qt Signals and Slots Work - Part 3 - Queued and Inter Thread Connections

A QueuedConnection will post an event to the event loop to eventually be handled.

When posting an event (in QCoreApplication::postEvent), the event will be pushed in a per-thread queue (QThreadData::postEventList). The event queue is protected by a mutex, so there is no race conditions when threads push events to another thread's event queue.

Once the event has been added to the queue, and if the receiver is living in another thread, we notify the event dispatcher of that thread by calling QAbstractEventDispatcher::wakeUp. This will wake up the dispatcher if it was sleeping while waiting for more events. If the receiver is in the same thread, the event will be processed later, as the event loop iterates.

关于c++ - Qt 的事件循环线程是安全的还是原子的?处理 `QueuedConnection` 时如何同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55615364/

相关文章:

linux - freeRTOS 和并行处理

c++ - QPushButton c++ 的动态 QGridLayout

C++ : call another method for default method argument

C++:使用 pstsdk 时获取 "error C2065: ' pst':未声明的标识符?

wpf - 不反射(reflect)在 UI 上的任务更新数据绑定(bind) OC

c++ - 线程和 fork : fgetc() blocks when reading from popen()-pipe

c++ - 在 CPP 中取反 INT_MIN

c++ - 什么是悲观?

c++ - 函数参数中的Qt智能指针

c++ - 按下鼠标按钮时如何生成 QRect?