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

#include
#include
#include


/*Compile only if 'F' is callable. F maybe function, lambda, or class with 
 * overrided operator() function. 
 */
template           typename = typename std::enable_if::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 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::value, F, F*>::type task;
    std::thread h;
    bool is_detached;
};

你可能感兴趣的:(C++)