【Boost】boost庫中thread多線程詳解4——談談recursive_mutex(遞迴式互斥量)

來源:互聯網
上載者:User

如果一個線程中可能在執行中需要再次獲得鎖的情況(例子:test_thread_deadlock),按常規的做法會出現死結
此時就需要使用遞迴式互斥量boost::recursive_mutex,例子(test_thread_recursivelock)來避免這個問題。boost::recursive_mutex不會產生上述的死結問題,只是是增加鎖的計數,但必須確保你unlock和lock的次數相同,其他線程才可能鎖這個mutex。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.