1. 程式人生 > >c++11 thread 封裝成簡單執行緒類

c++11 thread 封裝成簡單執行緒類

       這幾天學習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了