#include <iostream>
#include "Thread.h"
using namespace std;
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;
}
#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();
};
#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();
}
$g++-7 Thread.cpp main.cpp -std=c++17 -lpthread
