Boost教程(三)多线程

在Linux上,Boost使用多线程还得用到filesystem和system模块,否则会报错,可能是thread模块用到了它们,因此cmake这样写

1
2
3
4
5
6
find_package(Boost COMPONENTS filesystem system thread REQUIRED)

add_executable(${PROJECT_NAME} "main.cpp" )
target_link_libraries(untitled ${Boost_FILESYSTEM_LIBRARY}
${Boost_SYSTEM_LIBRARY}
${Boost_THREAD_LIBRARY})

头文件只需要#include <boost/thread.hpp>

对于ROS环境,库文件已经包含在${catkin_LIBRARIES}当中

join

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void thread_1(int n)
{
cout<<"slot1: "<<n<<endl;
}

void thread_2(int n)
{
cout<<"slot2: "<< 2*n<<endl;
}

int main()
{
int n = 13;
boost::thread th_1 = boost::thread(boost::bind(&thread_1,n));
th_1.join();
boost::thread th_2 = boost::thread(boost::bind(&thread_2,n));
th_2.join();

cout<<endl<<"end"<<endl;
return 0;
}

没有两个join()会有多种结果:

1
2
3
slot2: 26end

slot1: 13

1
2
3
slot1: end
13
slot2: 26
1
2
3
4
slot1: slot2: 13
26

end

可见几个线程的执行顺序乱套了,给两个线程都加join()才确定顺序是 线程1-线程2-主线程,如果只加一个,剩下两个线程的顺序还是不确定。

boost::condition

程序如下,main函数里要把上面两个线程的join交换一下,先执行线程2,这样在线程2里的随机数如果大于90,会唤醒线程1。如果先执行线程1,会一直阻塞,程序没法向下执行了。

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
boost::mutex mut;
boost::condition cond;
boost::mutex::scoped_lock _lock(mut);

void thread_1(int n)
{
while(true)
{
cond.wait(_lock);
cout<< "thread 1: "<<rand()%50 <<endl;
sleep(1);
}
}

void thread_2(int n)
{
int m;
while(true)
{
m = 50 + rand()%50;
cout<< "thread 2: "<< m <<endl;
if(m>90)
{
cond.notify_one();
cout<<"thread 2 wake thread 1 ";
}
sleep(1);
}
}

某次的测试结果:

1
2
3
4
5
6
7
thread 2: 65
thread 2: 93
thread 2 wake thread 1 thread 1: 35
thread 2: 86
thread 2: 92
thread 2 wake thread 1 thread 1: 49
thread 2: 71