QT 线程挂起和恢复

假设子线程发消息通知主线程执行一个很长的函数,而子线程又需要根据这个函数的返回值来做接下来的事情,那么就需要在子线程发出消息之后将子线程挂起,等主线程中的函数执行完毕再恢复子线程。
方法:使用QMutex 和QWaitCondition。
子线程:

//CMyThread.h
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
class CMyThread:public QThread
{
    Q_OBJECT
public:
    CMyThread(...);
    virtual ~CMyThread();
    //start execute thread function
    void startThread();
    //resume thread after suspend.
    void resume();
protected:
    void run()Q_DECL_OVERRIDE;
private:
    QMutex sync;
    QWaitCondition pauseCond;
    bool f_stop;
signals:
    void message();
};
//CMyThread.cpp
#include "CMyThread.h"
CMyThread::CMyThread(...)
{
}
CMyThread::~CMyThread()
{
    stopThread();
}

void CMyThread::startThread()
{
    if(!isRunning())
    {
        start();
    }
}

void CMyThread::resume()
{
    sync.lock();
    pauseCond.wakeAll();
    sync.unlock();
}
void CMyThread::run()
{
    f_stop = false;
    sync.lock();
    emit message();
    pauseCond.wait(&sync);//thread suspend until be waked up
    if(m_taskFinsihed){
        //doSomething();        
    }
    sync.unlock();
}

主线程

//CMainForm.cpp
void CMainForm::messageProc()
{
    m_taskFinsihed = doSomeThing();
    pMyThread->resume();//resume thread after task finished
}

猜你喜欢

转载自blog.csdn.net/weixin_42288671/article/details/82116645