QThread和windows 事件event一起使用,實現執行緒執行中休眠一定時間
阿新 • • 發佈:2018-12-22
class TestThread:public QThread { public: TestThread(QObject* parent = nullptr); virtual ~TestThread(); void Stop(); protected: void run() override; void FunOne(); void FunTwo(); void FunThree(); private: HANDLE h_event=nullptr; bool stoped = false; }; TestThread::TestThread(QObject* parent):QThread(parent) { h_event = CreateEvent(NULL, FALSE, FALSE, NULL); } TestThread::~TestThread() { CloseHandle(h_event); if(h_event != nullptr) { h_event = nullptr; } } void TestThread::Stop() { SetEvent(h_event); requestInterruption(); stoped = true; quit(); wait(); } void TestThread::run() { while(!QThread::currentThread()->isInterruptionRequested()) { if(!stoped) FunOne(); if(!stoped) FunTwo(); if(!stoped) FunThree(); if(WaitForSingleObject(h_event,1000) == WAIT_OBJECT_0) { break; } qDebug()<<"run"; } } void TestThread::FunOne() { WaitForSingleObject(h_event,1000); qDebug()<<"test one"; } void TestThread::FunTwo() { WaitForSingleObject(h_event,1000); qDebug()<<"test two"; } void TestThread::FunThree() { WaitForSingleObject(h_event,1000); qDebug()<<"test three"; }
Stop執行緒停止,也可以放在解構函式中完成。