#pragma once #include #include #include class ThreadEx { public: template ThreadEx(F&& f, Args&&... args); ~ThreadEx(); bool is_runing(); void cannel(); private: std::future fu_run; pthread_t fu_run_id; }; // the constructor just launches some amount of workers template inline ThreadEx::ThreadEx(F&& f, Args&&... args) { auto task = std::bind(std::forward(f), std::forward(args)...); fu_run = std::async(std::launch::async, [this, task](){ fu_run_id = pthread_self(); task(); }); } inline ThreadEx::~ThreadEx() { cannel(); } inline bool ThreadEx::is_runing() { return fu_run.valid() && (fu_run.wait_for(std::chrono::seconds(0)) != std::future_status::ready); } inline void ThreadEx::cannel() { if (is_runing()) { pthread_cancel(fu_run_id); fu_run.wait(); } }