QThread - 使用slot quit()退出线程 [英] QThread - Using a slot quit() to exit the thread

查看:2818
本文介绍了QThread - 使用slot quit()退出线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在线程完成运行时通知对象。但是,我不能让线程正确退出。我有以下代码:

I want to inform an object when a thread has finished running. However, I cannot get the thread to exit properly. I have the following code:

Processor.cpp

Processor.cpp

thread = new QThread;
tw = new ThreadWorker;
connect(tw, SIGNAL(updateStatus(QString)), this, SLOT(statusUpdate(QString)));
tw->doSetup(thread, strDic);
tw->moveToThread(thread);
thread->start();

while(thread->isRunning())
{
}

qDebug() << "Thread Finished";

ThreadWorker.cpp

ThreadWorker.cpp

void ThreadWorker::doSetup(QThread *thread, const string &path)
{
  _strPath = path;
  connect(thread, SIGNAL(started()), this, SLOT(run()));
  connect(this, SIGNAL(finished()), thread, SLOT(quit())); //tried terminate() also
}


void ThreadWorker::run()
{
  DirectorySearch dicSearch;
  vector<string> vecFileList = dicSearch.getFileList(_strPath);
  emit updateStatus("Directory Fetched");
  emit finished();
}

quit()槽似乎没有停止线程isFinished从不会返回true)。

The quit() slot does not seem to stop the thread (QThread::isFinished never returns true). Can someone guide me in the right direction?

(注意:ThreadWorker不会从QThread继承)

(Note: ThreadWorker does not inherit from QThread)

推荐答案

假设 Processor.cpp 正在主线程中运行, while(thread-> isRunning ) loop有你的主线程完全捆绑。这意味着你的应用程序的事件循环不能进行任何处理,所以信号 updateStatus()例如永远不会被处理。如注释中所述,由于 QThread 对象由主线程创建,其信号将不工作,因为它们也将需要主事件循环执行它事情。此外,如果你在你的主线程中等待你的工作线程做某事,为什么要使用一个工作线程呢? :)

Assuming that Processor.cpp is running in your main thread, the while(thread->isRunning()) loop has your main thread completely tied up. This means that your application's event loop cannot do any processing so the signalupdateStatus() for example, will never get processed. As mentioned in the comments, since the QThread object is created by the main thread, its signals won't work either since they will also require the main event loop to be doing its thing. Besides, if you are waiting in your main thread for your worker thread to do something, why use a worker thread at all? :)

尝试删除while循环,添加一个插槽 workDone() )到 Processor.cpp 并将其连接到您的 Threadworker finished code>信号。

Try removing the while loop, add a slot workDone() (or whatever you want to call it) to Processor.cpp and connect that to your Threadworker's finished() signal.

这篇关于QThread - 使用slot quit()退出线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆