有没有像boost一样的好用的开源线程池C++实现来用于生产代码中呢?
请提供示例代码或使用示例代码的链接。
有没有像boost一样的好用的开源线程池C++实现来用于生产代码中呢?
请提供示例代码或使用示例代码的链接。
我认为它仍未被纳入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
的销毁将等待所有线程完成。
pool tp(2);
中,2
的含义是什么? - Arun你可能想看一下http://threadpool.sourceforge.net/。
使用Boost.Thread实现线程池并不难。根据任务的不同,你可能会想要使用无锁队列中的容器,而不是标准模板库中的容器。例如,lock free
库中的fifo
容器。
祝你好运!
我已经写了一个小例子在这里。 基本上你需要做的就是实现这段代码:
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();
auto_ptr
!它是不安全的且已被废弃。 - Shivanshu Goyal我相信你可以使用boost::asio中的io_service来模拟一个线程池。您可以控制io_service池中可用的线程数,然后可以通过“post”将任务提交到io_service,由池中的一个线程执行。每个这样的任务必须是一个函数对象(我相信是这样的)。
我现在无法提供示例,但是asio文档中有关io_service池的内容将概述如何实现这一点。