您的位置:首页 > 其它

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

2013-09-01 16:15 471 查看
如果一个线程中可能在执行中需要再次获得锁的情况(例子:test_thread_deadlock),按常规的做法会出现死锁

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

[cpp] view
plaincopyprint?

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

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: