利用C++11实现线程task的简单封装

#include <functional>
#include <thread>
#include <type_traits>


/*Compile only if 'F' is callable. F maybe function, lambda, or class with 
 * overrided operator() function. 
 */
template <typename F,
          typename = typename std::enable_if<std::is_function<F>::value>>
class Task_base {
  public:
    Task_base() = delete;
    Task_base(F task) : task(task), is_detached(false) {}
    Task_base(F task, bool detached) : task(task), is_detached(detached) {}

    template <typename T, typename... Args> void run(T v1, Args... rest) {
        std::thread t(task, v1, rest...);
        h = std::move(t);
        if (is_detached)
            h.detach();
    }

    void run() {
        std::thread t(task);
        h = std::move(t);
        if (is_detached)
            h.detach();
    }

    ~Task_base() {
        if (h.joinable())
            h.join();
    }

  private:
    // If 'F' is a class or lambda, task is of type F. 
    // If 'F' is function, then task is of type F*.
    typename std::conditional<std::is_class<F>::value, F, F*>::type task;
    std::thread h;
    bool is_detached;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值