多线程 join

使用Windows写Boost多线程时,还需要先编译Boost源码产生库文件,我试了几次都没成功,就懒得在Windows上编程了。

在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

使用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

可见几个线程的执行顺序乱套了,执行顺序是    线程1 ——线程 1的join()—— 线程2 ——线程 2的join()    才确定顺序是 线程1-线程2-主线程,如果只加一个,或者先定义两个线程,再执行两个join,线程的顺序还是不确定。