#include <iostream>
void run()
{
for (int i = 0; i < 10; ++i)
{
std::cout << i << std::endl;
}
}
int main(int argc, char* argv[])
{
boost::thread theard1(&run);
boost::thread theard2(&run);
boost::thread theard3(&run);
theard1.join();
theard2.join();
theard3.join();
return 0;
}
结果:
0
1
2
3
00
11
22
37
48
59
6
37
4
8
5
9
6
7
8
9
杂乱无章的,一个线程执行输出时被其他线程干扰.
#include <boost/thread/thread.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <iostream>
boost::recursive_mutex io_mutex;
void run()
{
boost::recursive_mutex::scoped_lock lock(io_mutex);
for (int i = 0; i < 10; ++i)
{
std::cout << i << std::endl;
}
}
int main(int argc, char* argv[])
{
boost::thread theard1(&run);
boost::thread theard2(&run);
boost::thread theard3(&run);
theard1.join();
theard2.join();
theard3.join();
return 0;
}
结果:
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
当一个线程被Lock,其他线程只能等待.