Boost - 多线程-boost recursive_mutex用法

来源:互联网 发布:ape播放软件 编辑:程序博客网 时间:2024/06/10 09:34

http://cooker.iteye.com/blog/748826

Author:QQ174554431


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

C++代码  收藏代码
  1. #include <iostream>    
  2.    
  3. void run()  
  4. {    
  5.     for (int i = 0; i < 10; ++i)    
  6.     {    
  7.         std::cout << i << std::endl;    
  8.     }    
  9. }    
  10.   
  11.   
  12.     
  13. int main(int argc, char* argv[])    
  14. {    
  15.     boost::thread theard1(&run);    
  16.     boost::thread theard2(&run);    
  17.     boost::thread theard3(&run);   
  18.     theard1.join();    
  19.     theard2.join();    
  20.     theard3.join();   
  21.     return 0;    
  22. }    



结果:
0
1
2
3
00


11


22


37

48

59

6
37
4
8
5
9
6

7
8
9

杂乱无章的,一个线程执行输出时被其他线程干扰.


C++代码  收藏代码
  1. #include <boost/thread/thread.hpp>    
  2. #include <boost/thread/recursive_mutex.hpp>  
  3. #include <iostream>    
  4.   
  5. boost::recursive_mutex io_mutex;    
  6.    
  7. void run()  
  8. {    
  9.     for (int i = 0; i < 10; ++i)    
  10.     {    
  11.         boost::recursive_mutex::scoped_lock  lock(io_mutex);  
  12.         std::cout << i << std::endl;    
  13.     }    
  14. }    
  15.   
  16.   
  17.     
  18. int main(int argc, char* argv[])    
  19. {    
  20.     boost::thread theard1(&run);    
  21.     boost::thread theard2(&run);    
  22.     boost::thread theard3(&run);   
  23.     theard1.join();    
  24.     theard2.join();    
  25.     theard3.join();   
  26.     return 0;    
  27. }    




结果:
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

输出时锁定, 就不会杂乱无章节.








C++代码  收藏代码
  1. #include <boost/thread/thread.hpp>    
  2. #include <boost/thread/recursive_mutex.hpp>  
  3. #include <iostream>    
  4.   
  5. boost::recursive_mutex io_mutex;    
  6.    
  7. void run()  
  8. {    
  9.     boost::recursive_mutex::scoped_lock  lock(io_mutex);  
  10.     for (int i = 0; i < 10; ++i)    
  11.     {    
  12.         std::cout << i << std::endl;    
  13.     }    
  14. }    
  15.   
  16.   
  17.     
  18. int main(int argc, char* argv[])    
  19. {    
  20.     boost::thread theard1(&run);    
  21.     boost::thread theard2(&run);    
  22.     boost::thread theard3(&run);   
  23.     theard1.join();    
  24.     theard2.join();    
  25.     theard3.join();   
  26.     return 0;    
  27. }    



结果:
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,其他线程只能等待.