您的位置:首页 > 编程语言 > C语言/C++

c++11 线程池系列之一 最简单的线程池

2015-11-28 16:48 363 查看
线程池最简单的形式是含有一个固定数量的工作线程来处理任务,典型的数量是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会在另一文章中单独给出
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++11 线程 线程池