【Boost】boost库中thread多线程详解4——谈谈recursive_mutex

如果一个线程中可能在执行中需要再次获得锁的情况(例子:test_thread_deadlock),按常规的做法会出现死锁
此时就需要使用递归式互斥量boost::recursive_mutex,例子(test_thread_recursivelock)来避免这个问题。boost::recursive_mutex不会产生上述的死锁问题,只是是增加锁的计数,但必须确保你unlock和lock的次数相同,其他线程才可能锁这个mutex。

[cpp]  view plain  copy
 print ?
  1. namespace {  
  2.     boost::mutex g_mutex;    
  3.       
  4.     void threadfun1()  
  5.     {  
  6.         PRINT_DEBUG("enter threadfun1...");  
  7.         boost::lock_guard<boost::mutex> lock(g_mutex);  
  8.         PRINT_DEBUG("execute threadfun1...");  
  9.     }    
  10.       
  11.     void threadfun2()  
  12.     {  
  13.         PRINT_DEBUG("enter threadfun2...");  
  14.         boost::lock_guard<boost::mutex> lock(g_mutex);  
  15.         threadfun1();  
  16.         PRINT_DEBUG("execute threadfun2...");  
  17.     }  
  18. }  
  19.   
  20. namespace {  
  21.     boost::recursive_mutex g_rec_mutex;  
  22.   
  23.     void threadfun3()  
  24.     {  
  25.         PRINT_DEBUG("enter threadfun3...");  
  26.         boost::recursive_mutex::scoped_lock lock(g_rec_mutex);  
  27.         // 当然这种写法也可以  
  28.         // boost::lock_guard<boost::recursive_mutex> lock(g_rec_mutex);  
  29.         PRINT_DEBUG("execute threadfun3...");  
  30.     }    
  31.   
  32.     void threadfun4()  
  33.     {  
  34.         PRINT_DEBUG("enter threadfun4...");  
  35.         boost::recursive_mutex::scoped_lock lock(g_rec_mutex);  
  36.         threadfun3();  
  37.         PRINT_DEBUG("execute threadfun4...");  
  38.     }  
  39. }  
  40.   
  41. // 死锁的例子  
  42. void test_thread_deadlock()  
  43. {  
  44.     threadfun2();  
  45. }  
  46.   
  47. // 利用递归式互斥量来避免这个问题  
  48. void test_thread_recursivelock()  
  49. {  
  50.     threadfun4();  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值