這幾天學習qt的時候發現Qt的線程類和java的線程類差不多,因爲要讀取攝像頭然後顯示到界面上,線程需要不停的讀。大體結構就是這樣了:
void run(){
while( !當前線程被中斷){
//work
}
}
主線程要想停止線程就
thread->Interrupted()
只是簡單的封裝了一下,複雜的功能還要自己添加,不多說了,直接上代碼
#include <thread>
#include <atomic>
class Thread
{
public:
Thread();
virtual ~Thread();
void start();
std::thread::id getId();
void interrupt();
bool isInterrupted();
void join();
virtual void run();
private:
std::atomic<bool> isInterript = false;
std::thread th;
};
#include "Thread.h"
Thread::Thread()
{
}
Thread::~Thread()
{
if (!this->isInterrupted())
{
this->interrupt();
}
if (this->th.joinable()) {
this->th.join();
}
}
void Thread::start()
{
std::thread thr(std::bind(&Thread::run,this));
this->th = std::move(thr);
}
std::thread::id Thread::getId()
{
return this->th.get_id();
}
void Thread::interrupt()
{
this->isInterript = true;
}
bool Thread::isInterrupted()
{
return this->isInterript;
}
void Thread::join()
{
this->th.join();
}
void Thread::run()
{
}
我們想要用多線程的時候,就直接繼承它,然後重寫一下run方法就行了
#include "Thread.h"
class MyThread :
public Thread
{
public:
MyThread();
virtual ~MyThread();
virtual void run() override;
};
#include "MyThread.h"
#include <iostream>
MyThread::MyThread()
{
}
MyThread::~MyThread()
{
}
void MyThread::run()
{
while (!this->isInterrupted())
{
std::cout << "MyThread" << std::endl;
}
}
然後主函數調用
#include <iostream>
#include "MyThread.h"
int main(int argc, char** argv)
{
MyThread th;
th.start();
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "這是主線程" << std::endl;
th.interrupt();
return 0;
}
這樣我們就不用join這個線程了,只要中斷這個服務線程,然後它自己在析構的時候就自動join了