Boost - 多线程-boost recursive_mutex用法

1277 篇文章 12 订阅
831 篇文章 16 订阅
Author:QQ174554431

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

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



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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值