Ami*_*hum 42 c++ multithreading boost boost-thread threadpool
什么是C++在生产代码中使用的线程池的良好开源实现(类似于boost)?
请提供您自己的示例代码或示例代码使用的链接.
Die*_*lla 21
我认为它仍然没有被Boost接受,但是一个很好的注意点: 线程池.一些使用示例,来自网站:
#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.
}
Run Code Online (Sandbox Code Playgroud)
池中的参数"2"表示线程数.在这种情况下,tp等待所有线程完成的销毁.
小智 9
你可能想看看http://threadpool.sourceforge.net/
使用Boost.Thread自己实现线程池并不困难.根据任务的不同,您可能希望对队列使用无锁容器,而不是标准模板库中的容器.例如,库中的容器.fifolock 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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45004 次 |
| 最近记录: |