关于多线程:为什么在QThread(事件循环)之外调用QTimer :: start()不会失败?

Why is a call to QTimer::start() outside a QThread (event loop) not failing?

该文件说

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.

所以我希望这段代码...

1
2
3
4
5
6
7
8
9
int main(int argc, char *argv[])
{
  QCoreApplication app(argc, argv);
  QTimer timer;
  timer.start(1000);

  app.exec();

}

...失败,因为我在其中调用start的主线程不是QThreadTimers can only be used with threads started with QThread

为什么这不会失败?


似乎您没有正确理解文档所指示的内容,让我们分析语句的每个部分:

In multithreaded applications, you can use QTimer in any thread that has an event loop.

您在哪里使用了QTimer的事件循环? 是的,您正在主线程中使用QTimer,并且已通过QXApplication创建了事件循环。

To start an event loop from a non-GUI thread, use QThread::exec()

主线程是非GUI线程吗? 不,因此在这种情况下,不必在主线程中使用QThread来使用QTimer。

QTimer在什么情况下会失败? 如果QTimer在主线程中运行,而您尚未创建QXApplication,或者在没有Qt事件循环的std :: thread线程中运行它。

结论:

如果在主线程中使用了QTimer,则只需运行QXApplication,如果要在另一个线程中使用它,则必须使用QThread。 换句话说,QTimer仅在存在Qt事件循环的情况下起作用。