c++11,线程池之二--有等待线程池中任务完成功能的线程池
2015-11-28 19:55
501 查看
#include <deque> #include <future> #include <memory> #include <functional> #include <iostream> #include <iostream> class function_wrapper { struct impl_base { virtual void call()=0; virtual ~impl_base() {} }; std::unique_ptr<impl_base> impl; template<typename F> struct impl_type: impl_base { F f; impl_type(F&& f_): f(std::move(f_)) {} void call() { f(); } }; public: template<typename F> function_wrapper(F&& f): impl(new impl_type<F>(std::move(f))) {} void call() { impl->call(); } function_wrapper(function_wrapper&& other): impl(std::move(other.impl)) {} function_wrapper& operator=(function_wrapper&& other) { impl=std::move(other.impl); return *this; } function_wrapper(const function_wrapper&)=delete; function_wrapper(function_wrapper&)=delete; function_wrapper& operator=(const function_wrapper&)=delete; };
class thread_pool { public: std::deque<function_wrapper> work_queue; template<typename FunctionType> std::future<typename std::result_of<FunctionType()>::type> submit(FunctionType f) { typedef typename std::result_of<FunctionType()>::type result_type; std::packaged_task<result_type()> task(std::move(f)); std::future<result_type> res(task.get_future()); work_queue.push_back(std::move(task)); return res; } public: thread_pool(): joiner(threads) { done.store(false); unsigned const thread_count=std::thread::hardware_concurrency(); try { for(unsigned i=0;i<thread_count;++i) { threads.push_back( std::thread(&thread_pool::worker_thread,this)); } } catch(...) { done=true; throw; } } ~thread_pool() { done=true; } template<typename FunctionType> void submit(FunctionType f) { work_queue.push(std::function<void()>(f)); } };
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- C#线程间不能调用剪切板的解决方法
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C#多线程学习之(四)使用线程池进行多线程的自动管理
- C#线程同步的三类情景分析
- C#获取进程或线程相关信息的方法
- C#停止线程的方法
- C#子线程更新UI控件的方法实例总结
- C#线程队列用法实例分析
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题