c++11 线程池系列之一 最简单的线程池
来源:互联网 发布:地狱之眼优化技能特效 编辑:程序博客网 时间:2024/06/14 16:57
线程池最简单的形式是含有一个固定数量的工作线程来处理任务,典型的数量是std::thread::hardware_concurrency().
当有任务要处理时,调用一个函数将任务放到等待队列中。每个工作线程都是从该队列中取出任务,执行完任务后继续从等待队列取出更多的任务来处理。在最简单的情况,没有办法来等待一个任务完成。如需要这样的功能,则需要用户自己维护同步。
下面上代码
class thread_pool{ std::atomic_bool done; thread_safe_queue<std::function<void()> > work_queue; std::vector<std::thread> threads; join_threads joiner; void worker_thread() { while(!done) { std::function<void()> task; if(work_queue.try_pop(task)) { task(); } else { std::this_thread::yield(); } } }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)); }};
其中jointhread与thread_safe_queue会在另一文章中单独给出
1 0
- c++11 线程池系列之一 最简单的线程池
- 最简单的C线程池
- 最简单的线程池
- c++11 线程池系列之一 所需要的thread_safe_queue
- c++11 线程池系列之一 所需要的join_threads
- c++ 11 多线线程系列-------- 一个最简单而且实用的线程池
- 线程池的最简单的解释
- 线程池最简单用法
- 简单Linux C线程池的实现
- [C++]_[线程池的简单实现]
- c语言线程池的简单实现
- C语言实现简单的线程池
- 简单C语言线程池的编写
- 简单Linux C线程池
- 简单Linux C线程池
- 简单Linux C线程池
- 简单Linux C线程池
- 简单Linux C线程池
- Python3.5+Django1.8链接Mysql数据库的方法
- Struts2模型驱动的一个问题
- JAVA反射机制实例教程
- javascript动态添加、删除按钮和input输入框
- Android属性之build.prop生成过程分析
- c++11 线程池系列之一 最简单的线程池
- Unity官方实例教程 Space Shooter
- AtomicLong
- CSS选择器详解(伪类)
- QEMU 简介(一)
- 程序员,这12个问题让经理比你痛苦多了
- VirtualBox 在CentOS下安装增强功能及错误解决
- css text文本属性(四)
- 增强for循环用法