Encapsulating c++11 thread as a simple thread class

When learning QT these days, I found that QT's thread class is similar to java's thread class, because to read the camera and then display it on the interface, the thread needs to keep reading. This is the general structure:

void run(){

    while( !Current thread interrupted){

    //work

    }

}

If the main thread wants to stop the thread

thread->Interrupted()

It's just a simple encapsulation. You need to add complex functions by yourself. Let's not talk about it. Just go to the code

#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()
{

}

 

When we want to use multithreading, we can directly inherit it, and then rewrite the run method

#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;
	}
}

Then the main function calls

#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 << "This is the main thread" << std::endl;

	th.interrupt();

	return 0;
}

In this way, we don't need to join the thread, just interrupt the service thread, and then it will join automatically when it is destructed

Tags: Qt Java

Posted on Fri, 31 Jan 2020 01:09:05 -0800 by Stinger51