如果一個線程中可能在執行中需要再次獲得鎖的情況(例子: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();}