如何在线程和子线程之间设置信号/插槽连接?

时间:2014-09-14 16:53:42

标签: c++ multithreading qt

我的ParentThread课程来自QThread,其中包含以下run()方法,大致如下所示:

void ParentThread::run()
{
  QThread *childThread = new QThread;
  QObject::connect(childThread, SIGNAL(finished()), this, SLOT(onChildThreadFinished());
  QObject::connect(childThread, SIGNAL(finished()), childThread, SLOT(deleteLater());
  childThread->start();

  exec();
}

广告位onChildThreadFinished()ParentThread上定义,应在ParentThread的上下文中运行。但是,使用上面的代码,onChildThreadFinished仅在信号/插槽连接为Qt::DirectConnection时被调用,但随后在子线程的上下文中运行。如果信号/插槽连接定义为Qt::QueuedConnection,则永远不会调用插槽。我使用的是Qt 4.8.5。知道这里的问题是什么吗?

1 个答案:

答案 0 :(得分:1)

您声明插槽onChildThreadFinished()是在ParentThread上定义的,应该在ParentThread 的上下文中运行。这个假设是错误的。这是不鼓励继承子QThread的原因之一。

如果你想在你的线程中使用插槽,那么子类化QThread就不是你想要做的。请改用worker-object方法。子类QObject并调用QObject::moveToThread将您的对象移动到新线程。

以下是Qt文档对此的评论:

It is important to remember that a QThread instance lives in the old thread that instantiated it, not in the new thread that calls run(). This means that all of QThread's queued slots will execute in the old thread. Thus, a developer who wishes to invoke slots in the new thread must use the worker-object approach; new slots should not be implemented directly into a subclassed QThread.