Boost - 多线程-boost recursive_mutex用法


Author:QQ174554431

比较一下,就知道这个函数怎么用,效果如何.


#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()
{  
	for (int i = 0; i < 10; ++i)  
	{  
		boost::recursive_mutex::scoped_lock  lock(io_mutex);
		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
0
2
1
3
4
5
6
2
7
3
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,其他线程只能等待.




你可能感兴趣的:(多线程,thread,C++,c,C#)