c++ thread pool相关总结
boost::threadpool
按照boost标准开发的第三方库。下载地址在http://threadpool.sourceforge.net/。使用方法较为简单。例子如下
#include <iostream>
#include "boost/bind.hpp"
#include "boost/threapool.hpp"
using namespace std;
using namespace threadpool;
void first_task()
{
cout << "first task" << endl;
}
void second_task()
{
cout << "second task" << endl;
}
void task_with_parameter(int value,string str)
{
cout << "task with parameter,value is: " << value <<",str is: " << str;
}
int main()
{
// 声明线程池
pool thread_pool(2);
// 向线程池中添加任务
thread_pool.schedule(&first_task);
// 等待线程函数执行完成
thread_pool.wait();
thread_pool.schedule(&second_task);
thread_pool.schedule(boost::bind(task_with_parameter,8,"hello"));
thread_pool.wait();
return 0;
}
boost::threadpool 添加任务,同步方式都相对简单,在添加多参数的任务时候需要注意 boost::bind() 传递的参数是按照拷贝的方式传递的。如果想使用引用的方式传递的话,