#include <iostream>
#include <string>
#include <thread>
#include "boost/noncopyable.hpp"
class Thread : public boost::noncopyable {
public:
Thread() {
started_ = false;
joined_ = false;
}
virtual ~Thread() {
started_ = false;
joined_ = true;
if (thd_.joinable()) {
std::cout << "thread detach." << std::endl;
thd_.detach();
}
}
inline void set_thread_id(const std::string &id) {
thd_id_ = id;
}
inline void get_thread_id(std::string &id) const {
id = thd_id_;
}
inline bool is_started() const {
return started_;
}
inline void join() {
if (false == joined_ && thd_.joinable()) {
joined_ = true;
thd_.join();
}
}
void start() {
started_ = true;
thd_ = std::thread(std::bind(&Thread::thread_body, this));
}
protected:
virtual void run() = 0;
private:
void thread_body() {
try {
run();
}
catch (std::exception &e) {
std::cerr << "thread exception = " << e.what() << std::endl;
}
catch (...) {
std::cerr << "unknown thread exception." << std::endl;
throw;
}
}
private:
std::string thd_id_;
std::thread thd_;
bool started_;
bool joined_;
};
class SayHelloThread : public Thread {
protected:
virtual void run() override {
std::cout << "hello thread." << std::endl;
}
};
int main() {
std::string id = "12";
SayHelloThread hello_thread;
hello_thread.set_thread_id(id);
hello_thread.start();
hello_thread.join();

return 0;
}