线程池 boost::thread_group

thread_group用于管理一组线程,就像是一个线程池,它内部使用std::list管理线程,使用shared_mutex来保护线程,所以它本身是线程安全的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <ros/ros.h>
#include <iostream>
#include <boost/ref.hpp>
#include <boost/thread/thread.hpp>
#include <string>
using namespace boost;
using namespace std;

shared_mutex s_mu; // 全局shared_mutex对象
mutex m;

int g_num = 10; // 全局变量



void func_1()
{
m.lock();
cout << "func_1: "<< g_num <<endl;
m.unlock();
}

void func_2()
{
m.lock();
cout << "func_2: "<< g_num * 2 <<endl;
m.unlock();
}

void func_3()
{
m.lock();
cout << "func_3: "<< g_num * 10 <<endl;
m.unlock();
}


int main()
{
boost::thread_group tg;
tg.create_thread(bind(&func_1) );
tg.create_thread(bind(&func_1) );

tg.create_thread(bind(func_2));
tg.create_thread(bind(func_3));
tg.join_all();

return 0;
}