【问题标题】:If i invoke QMetaObject::invokeMethod from thread to singletone is the invokation is still in that qthread?如果我从线程调用 QMetaObject::invokeMethod 到单音,调用是否仍在该 qthread 中?
【发布时间】:2012-01-31 13:39:31
【问题描述】:

我有线程(工作得很好)像这样在单音对象中调用方法:

bool bInvokeUpdate= QMetaObject::invokeMethod(ApiManager::getInstance(),
         "updateMainWindowTree",
         Qt::BlockingQueuedConnection,
         Q_RETURN_ARG(bool, bReturnUpdate))

;

我使用 Qt::BlockingQueuedConnection 所以我可以根据 bool 值继续线程工作.. 任何方式 我的问题是这个调用是否保留在线程中?还是导致方法在主线程中执行?

当我在线程中调试应用程序时,我在调试器中看到我在线程 id xxxx 中 但是当我在 updateMainWindowTree 方法中设置断点时,我看到它跳转到主线程。 那么我不断从主线程调用函数是什么意思?如何避免?

【问题讨论】:

  • 什么是 ApiManager,它驻留在哪里?
  • 它的全局对象,提供 API 功能,与 GUI 或其他东西无关,但也从 GUI 线程调用

标签: c++ multithreading qt qthread


【解决方案1】:

由于你使用了Qt::BlockingQueuedConnection,所以调用在QObjectApiManager::getInstance()所属的线程中执行。

如果该单例与调用代码属于同一个线程,则会出现死锁。

您可以使用Qt::DirectConnection 留在同一个线程中,但您的函数名称表明它与 GUI 有关,因此它应该在主线程中执行(意味着您当前的代码及其行为是可能都已经正确了)。

【讨论】:

  • 从线程更新 GUI 以使用 "emit" 或 QMetaObject::invokeMethod 更好
  • 发出信号似乎比使用invokeMethod清晰得多,如果您不需要其他线程中槽的返回值。
猜你喜欢
  • 2020-04-05
  • 2021-07-11
  • 2010-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多