c++11 thread 封装成简单线程类

       这几天学习qt的时候发现Qt的线程类和java的线程类差不多,因为要读取摄像头然后显示到界面上,线程需要不停的读。大体结构就是这样了:

void run(){

    while( !当前线程被中断){

    //work

    }

}

        主线程要想停止线程就

thread->Interrupted()

只是简单的封装了一下,复杂的功能还要自己添加,不多说了,直接上代码

#include 
#include 

class Thread
{
public:
	Thread();
	virtual ~Thread();

	void start();
	std::thread::id getId();
	void interrupt();
	bool isInterrupted();
	void join();
	virtual void run();

private:
	std::atomic 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 

MyThread::MyThread()
{
}

MyThread::~MyThread()
{
}

void MyThread::run()
{
	while (!this->isInterrupted())
	{
		std::cout << "MyThread" << std::endl;
	}
}

然后主函数调用

#include 

#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了

你可能感兴趣的:(c++)