什么是 C++ 在生产代码中使用的线程池的良好开源实现(类似于 boost)?
请提供您自己的示例代码或示例代码用法的链接。
什么是 C++ 在生产代码中使用的线程池的良好开源实现(类似于 boost)?
请提供您自己的示例代码或示例代码用法的链接。
我认为它仍然没有被 Boost 接受,但是一个很好的起点: threadpool。一些使用示例,来自网站:
#include "threadpool.hpp"
using namespace boost::threadpool;
// Some example tasks
void first_task()
{
...
}
void second_task()
{
...
}
void third_task()
{
...
}
void execute_with_threadpool()
{
// Create a thread pool.
pool tp(2);
// Add some tasks to the pool.
tp.schedule(&first_task);
tp.schedule(&second_task);
tp.schedule(&third_task);
// Leave this function and wait until all tasks are finished.
}
池的参数“2”表示线程数。在这种情况下,销毁tp
等待所有线程完成。
你可能想看看http://threadpool.sourceforge.net/
使用Boost.Thread自己实现线程池并不难。根据任务的不同,您可能希望对队列使用无锁容器,而不是标准模板库中的容器。例如,库中的容器。fifo
lock free
祝你好运!
我在这里写了一个小例子。基本上你需要做的是实现这段代码:
asio::io_service io_service;
boost::thread_group threads;
auto_ptr<asio::io_service::work> work(new asio::io_service::work(io_service));
// Spawn enough worker threads
int cores_number = boost::thread::hardware_concurrency();
for (std::size_t i = 0; i < cores_number; ++i){
threads.create_thread(boost::bind(&asio::io_service::run, &io_service));
}
// Post the tasks to the io_service
for(vector<string>::iterator it=tasks.begin();it!=tasks.end();it++){
io_service.dispatch(/* YOUR operator()() here */);
}
work.reset();
我相信你可以在 boost::asio 中模拟一个带有 io_service 的线程池。您可以控制 io_service 池可用的线程数,然后您可以将任务“发布”到 io_service,这将由池中的一个线程执行。每个这样的任务都必须是一个函子(我相信)。
我现在不能在这里举一个例子,但是关于 io_service 池的 asio 文档将概述如何做到这一点。
这是一个使用线程池(基于 Boost 构建)的简单的仅包含标头的任务队列:taskqueue.hpp
TaskQueue 项目页面包含一个示例应用程序,演示如何使用它: