【Boost】boost库中thread多线程详解4——谈谈recursive_mutex(递归式互斥量)

来源:互联网 发布:用手机端口怎么查询 编辑:程序博客网 时间:2024/06/14 05:48
如果一个线程中可能在执行中需要再次获得锁的情况(例子:test_thread_deadlock),按常规的做法会出现死锁

此时就需要使用递归式互斥量boost::recursive_mutex,例子(test_thread_recursivelock)来避免这个问题。boost::recursive_mutex不会产生上述的死锁问题,只是是增加锁的计数,但必须确保你unlock和lock的次数相同,其他线程才可能锁这个mutex

  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();  
  51. }

阅读全文
0 0