天天看點

利用C++11實作線程task的簡單封裝

#include <functional>

#include <thread>

#include <type_traits>

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;

};

繼續閱讀