RAII 封装的 thread

class ThreadRAII
{
public:
    // whether join or detach should be called,
    // when a this object is destroyed.
    enum class DtorAction { join, detach };

    ThreadRAII(std::thread&& t, DtorAction a)
        : action_(a), t_(std::move(t)) {}

    ThreadRAII (ThreadRAII&&)           = default;
    ThreadRAII& operator=(ThreadRAII&&) = default;

    ~ThreadRAII()
    {
        if (t_.joinable()) {
            if (action_ == DtorAction::join) {
                t_.join();
            } else {
                t_.detach();
            }
        }
    }
    std::thread& get() { return t_; }
private:
    DtorAction  action_;
    std::thread t_;
};

 

posted @ 2016-02-14 01:27  wu_overflow  阅读(287)  评论(0编辑  收藏  举报