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线程停止,也可以放在析构函数中完成。