日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2024/4/11 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Boost】boost库中thread多线程详解4——谈谈recursive_mutex 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如果一個線程中可能在執行中需要再次獲得鎖的情況(例子:test_thread_deadlock),按常規的做法會出現死鎖
此時就需要使用遞歸式互斥量boost::recursive_mutex,例子(test_thread_recursivelock)來避免這個問題。boost::recursive_mutex不會產生上述的死鎖問題,只是是增加鎖的計數,但必須確保你unlock和lock的次數相同,其他線程才可能鎖這個mutex。

[cpp]?view plaincopy print?
  • namespace?{??
  • ????boost::mutex?g_mutex;????
  • ??????
  • ????void?threadfun1()??
  • ????{??
  • ????????PRINT_DEBUG("enter?threadfun1...");??
  • ????????boost::lock_guard<boost::mutex>?lock(g_mutex);??
  • ????????PRINT_DEBUG("execute?threadfun1...");??
  • ????}????
  • ??????
  • ????void?threadfun2()??
  • ????{??
  • ????????PRINT_DEBUG("enter?threadfun2...");??
  • ????????boost::lock_guard<boost::mutex>?lock(g_mutex);??
  • ????????threadfun1();??
  • ????????PRINT_DEBUG("execute?threadfun2...");??
  • ????}??
  • }??
  • ??
  • namespace?{??
  • ????boost::recursive_mutex?g_rec_mutex;??
  • ??
  • ????void?threadfun3()??
  • ????{??
  • ????????PRINT_DEBUG("enter?threadfun3...");??
  • ????????boost::recursive_mutex::scoped_lock?lock(g_rec_mutex);??
  • ????????//?當然這種寫法也可以??
  • ????????//?boost::lock_guard<boost::recursive_mutex>?lock(g_rec_mutex);??
  • ????????PRINT_DEBUG("execute?threadfun3...");??
  • ????}????
  • ??
  • ????void?threadfun4()??
  • ????{??
  • ????????PRINT_DEBUG("enter?threadfun4...");??
  • ????????boost::recursive_mutex::scoped_lock?lock(g_rec_mutex);??
  • ????????threadfun3();??
  • ????????PRINT_DEBUG("execute?threadfun4...");??
  • ????}??
  • }??
  • ??
  • //?死鎖的例子??
  • void?test_thread_deadlock()??
  • {??
  • ????threadfun2();??
  • }??
  • ??
  • //?利用遞歸式互斥量來避免這個問題??
  • void?test_thread_recursivelock()??
  • {??
  • ????threadfun4();??
  • }?
  • 總結

    以上是生活随笔為你收集整理的【Boost】boost库中thread多线程详解4——谈谈recursive_mutex的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。