gpt4 book ai didi

multithreading - 在 QThread 中需要调用 QThread.exec() 方法吗?

转载 作者:行者123 更新时间:2023-12-04 15:05:07 24 4
gpt4 key购买 nike

我不是在打电话 exec()在我的代码中,但 timerQUdpSocket工作正常。是 exec()用于等待 event接着说?

更新:timer正在工作,因为我没有调用 moveToThread(this)QThread ,这意味着 QThread实际上仍然是 main thread 的一部分.至于QUdpSocket好吧,我使用投票 functions .所以它不需要使用 signals .

提示:如果您需要做 init东西,这需要 event loop在您的 QThread ,您可以 delay调用 moveToThread直到您不需要 signals不再,这在程序加载时很实用。您也不需要在构造函数中调用它(例如,您可以在 run() 中调用它),只需复制 this QThread指向变量的指针并使 call稍后/其他地方使用指针。

最佳答案

您的计时器和套接字可能正在使用调用 QCoreApplication::exec() 时启动的主事件循环。 .尽管我确信在线程内运行事件循环有充分的理由,但我想不出一个。

QThread documentation状态:

Each QThread can have its own event loop. You can start the event loop by calling exec(); you can stop it by calling exit() or quit(). Having an event loop in a thread makes it possible to connect signals from other threads to slots in this thread, using a mechanism called queued connections. It also makes it possible to use classes that require the event loop, such as QTimer and QTcpSocket, in the thread. Note, however, that it is not possible to use any widget classes in the thread.



如果没有事件循环,就有可能发出由 GUI 线程或包含事件循环的不同线程处理的信号。这意味着线程必须有一个事件循环才能使其槽有效。根据上面的文档,一些类,如 QTimer ,需要一个正在运行的事件循环,你必须调用 QThread::exec() .其他类,如 QTCPSocket根据所使用的函数,可以在有或没有事件循环的情况下运行。类的文档应该说明它们有什么要求(如果有的话)。

关于multithreading - 在 QThread 中需要调用 QThread.exec() 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2339736/

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