gpt4 book ai didi

QTimer 线程亲和性

转载 作者:行者123 更新时间:2023-12-02 04:34:12 29 4
gpt4 key购买 nike

文档中说:

In multithreaded applications, you can use QTimer in any thread that has an event loop. To start an event loop from a non-GUI thread, use QThread::exec(). Qt uses the timer's thread affinity to determine which thread will emit the timeout() signal. Because of this, you must start and stop the timer in its thread; it is not possible to start a timer from another thread.

因此,当我有一个 QTimer 对象时,Qt 使用该对象(或其父对象)的线程亲和性来确定哪个线程将发出 timeout() 信号。
但是,当我使用不需要 QTimer 实例的静态成员函数 singleShot(..) 时会发生什么,然后哪个线程会发出超时信号?

最佳答案

Qt 是开源的,所以最好的方法是检查 source code .所以 internal class QSingleShotTimer 的对象已创建(它是 QObject 但不是 QTimer)。
回答您问题的最重要的行是 here :

  connect(this, SIGNAL(timeout()), receiver, member);

没有 moveToThread 所以它是这样工作的:

  1. 为当前线程创建临时对象
  2. 信号从那个线程发出
  3. 如果目标对象被分配给同一个线程,槽会立即被调用
  4. 否则槽调用在目标所属线程的事件循环中排队。

参见 connect 的文档及其 5-th parameter (type of connection) 的值.

请注意,如果 msec 值为零,则槽的调用在接收器所属的线程的偶数循环中排队(不创建临时对象)。

关于QTimer 线程亲和性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22320655/

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