If you have been looking for the C++ thread class that looks similar to the Thread classes in Java or Qt threads, I'm sure you will find this interesting:
#include <iostream>
#include <thread>
using namespace std;
class Thread {
private:
thread *pThread;
bool stopped;
void run();
public:
Thread();
~Thread();
void start();
void stop();
void join();
void detach();
};
This is a wrapper class that works as a convenience class for the C++ thread support library in this book. The Thread::run() method is our user-defined thread procedure. As I don't want the client code to invoke the Thread::run() method directly, I have declared the run method private. In order to start the thread, the client code has to invoke the start method on the thread object.
The corresponding Thread.cpp source file looks like this:
#include "Thread.h"
Thread::Thread() {
pThread = NULL;
stopped = false;
}
Thread::~Thread() {
delete pThread;
pThread = NULL;
}
void Thread::run() {
while ( ! stopped ) {
cout << this_thread::get_id() << endl;
this_thread::sleep_for ( 1s );
}
cout << "\nThread " << this_thread::get_id()
<< " stopped as requested." << endl;
return;
}
void Thread::stop() {
stopped = true;
}
void Thread::start() {
pThread = new thread( &Thread::run, this );
}
void Thread::join() {
pThread->join();
}
void Thread::detach() {
pThread->detach();
}
From the previous Thread.cpp source file, you will have understood that the thread can be stopped when required by invoking the stop method. It is a simple yet decent implementation; however, there are many other corner cases that need to be handled before it can be used in production. Nevertheless, this implementation is good enough to understand the thread concepts in this book.
Cool, let's see how our Thread class can be used in main.cpp:
#include "Thread.h"
int main() {
Thread thread1, thread2, thread3;
thread1.start();
thread2.start();
thread3.start();
thread1.detach();
thread2.detach();
thread3.detach();
this_thread::sleep_for ( 3s );
thread1.stop();
thread2.stop();
thread3.stop();
this_thread::sleep_for ( 3s );
return 0;
}
I have created three threads, and the way the Thread class is designed, the thread will only start when the start function is invoked. The detached threads run in the background; usually, you need to detach a thread if you would like to make the threads daemons. However, these threads are stopped safely before the application quits.