gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:17:17 25 4
gpt4 key购买 nike

假设 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com