如何告诉QThread等到工作完成后再完成? [英] How to tell QThread to wait until work is done ,and then finish?

查看:55
本文介绍了如何告诉QThread等到工作完成后再完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用一个工作线程的简单应用程序.启动此工作线程并初始化DownloadManager,该DownloadManager负责从网上下载文件.在我的主应用程序类中,在DownloadManager完成之前发出的线程上具有finish()信号.

I have a simple application that uses one worker thread. This worker thread is started and initializes DownloadManager, which is responsible for downloading files from the net. In my main application class I have the finished() SIGNAL on the thread that is emitted before the DownloadManager finishes.

我的问题是如何使工作线程一直等到DownloadManager完成工作.

My question is how to make the worker thread wait until the DownloadManager finishes its work.

这是示例代码:

 class Main
 {
     m_DownloadWorker = new DownloadWorker(this);
     QObject::connect(pm_hotosDownloadWorker, SIGNAL(finished()), this, SLOT(DownloadWorkerFinished()));
     m_DownloadWorker->Execute();
     // do i need to do here something so the thread will wait ?

     .....


    void Main::DownloadWorkerFinished()
    {
        Log("DownloadWorkerFinished");
    }
 };


 class DownloadWorker : public QThread
 {
     void DownloadWorker::Execute()
     {

         // do i need to do here somthing so the thread will wait ? 
        start();
     }

     void DownloadWorker::run()
     {
         // do i need to do here somthing so the thread will wait ?
        DownloadManager* pDownloadManager = new DownloadManager(this);
        pDownloadManager->download();


     }
 };

 class DownloadManager: public QObject
 {
     // downloading stuff using Qt networkmanager 

     .....
     .....
 }

推荐答案

您可以使用 QThread :: exec()调用以在事件循环中运行线程.线程将一直运行它,直到您通过调用 QThread :: exit告诉线程退出.).因此,一些示例代码可能如下所示:

You can use QThread::exec() call to run your thread in the event loop. The thread will run it until you tell your thread to exit by calling QThread::exit(). So some sample code can look like this:

void DownloadWorker::run()
 {
    DownloadManager* pDownloadManager = new DownloadManager(this);
    connect(pDownloadManager, SIGNAL(finished()), SLOT(exit()));
    connect(pDownloadManager, SIGNAL(error()), SLOT(exit()));
    pDownloadManager->download();
    exec();
 }

这将确保您在发出DownloadManager的"finished()"信号之前不会退出线程.

That would guarantee you that your thread won't quit until the "finished()" signal of your DownloadManager is issued.

注意:这里我举了一个如何解决您的问题的示例,但我不知道您的整个应用程序代码.这意味着不能保证此代码是线程安全的和一致的.您需要自己照顾互斥锁和所有正确的同步.要特别小心 !使用这样的低级"线程API可以很好地理解多重阅读.

Note: Here I put an example of how to solve your problem but I don't know your whole app code. That means there is not guarantee this code is thread safe and consistent. You need to take care of the mutexes and all the correct synchronization yourself. Be very careful ! Working with such a "low level" thread API requites good understanding of multithereading.

希望有帮助

这篇关于如何告诉QThread等到工作完成后再完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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