一、 boost库版本
二、boost库安装
- 下载源码 boost_1_69_0.tar.bz2
- 解压安装: ./bootstrap.sh; ./b2 install
三、牛刀小试
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <thread>
#include <boost/asio/thread_pool.hpp>
#include <boost/asio/post.hpp>
#include <boost/bind.hpp>
#include <boost/thread/pthread/thread_data.hpp>
using namespace std;
void task_1()
{
cout << "ttask_1 start: " <<std::this_thread::get_id() << endl;
for (int i = 0; i < 10; i++)
{
cout << "hello task_1" << endl;
sleep(1);
}
}
void task_2()
{
sleep(2);
cout << "task_2 start:" << std::this_thread::get_id()<<endl;
for (int i = 0; i < 5; i++)
{
cout << "hello task_2" << endl;
sleep(1);
}
}
void task_addParam(int a)
{
sleep(2);
cout << "task_3 start:" << std::this_thread::get_id()<<endl;
for (int i = 0; i < 5; i++)
{
cout <<"a + "<<i<<": "<<a + i << endl;
sleep(1);
}
}
int main()
{
boost::asio::thread_pool tp(3);
boost::asio::post(tp, task_1);
boost::asio::post(tp, task_2);
boost::asio::post(tp, boost::bind(task_addParam, 3));
tp.join();
return 0;
}
编译:
g++ -lboost_thread -o main thread_pool.cpp -I/usr/local/include -lpthread -std=c++11
输出:
ttask_1 start: 139705846953728
hello task_1
hello task_1
task_3 start:139705838561024
a + 0: 3
task_2 start:139705855346432
hello task_2
hello task_1
a + 1: 4
hello task_2
hello task_1
a + 2: 5
hello task_2
hello task_1
hello task_2
a + 3: 6
hello task_1
a + 4hello task_2: 7
hello task_1
hello task_1
hello task_1
hello task_1