thread

256 篇文章 3 订阅
149 篇文章 2 订阅
#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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值