boost::mutex vs boost::recursive_mutex
发布日期:2021-11-07 23:20:52 浏览次数:3 分类:技术文章

本文共 1427 字,大约阅读时间需要 4 分钟。

 

boost::mutex is not re-entrant, a thread can only lock it once, otherwise it’s dead-locked. The following code snippet demonstrates it:

#include "boost/thread/mutex.hpp"

#include <iostream>

boost::mutex mtx;

void bar(){

    boost::mutex::scoped_lock lLock(mtx);//!! dead-locked here

    std::cout << "bar" << std::endl;

}

void foo() {

    boost::mutex::scoped_lock lLock(mtx);

    std::cout << "foo" << std::endl;

    bar();

}

int _tmain(int argc, _TCHAR* argv[]){

    foo();

    return 0;

}

If you need re-entrant mutex, the boost::recursive_mutex is the choice. The following code snippet demonstrates it:

#include "boost/thread/recursive_mutex.hpp"

#include <iostream>

boost::recursive_mutex r_mtx;

void bar(){

    boost::recursive_mutex::scoped_lock lLock(r_mtx);//no problem for a thread to lock more than once

    std::cout << "bar" << std::endl;

}

void foo() {

boost::recursive_mutex::scoped_lock lLock(r_mtx);

    std::cout << "foo" << std::endl;

    bar();

}

int _tmain(int argc, _TCHAR* argv[]){

    foo();

    return 0;

}

I also did a benchmark on my PC. For 1 locking operation, the result is approximately: boost::mutex: 0.043 micro second, boost::recursive_mutex: 0.068 micro second.

Re-entrant mutex is the default in Java and C#. Generally speaking, if a mutex is shared by many modules/classes, it’s recommended to use boost::recursive_mutex; while if it’s only used by a single module/class and no re-entrant feature needed, it’s recommended to use boost::mutex

转载地址:https://blog.csdn.net/zhangwu416826/article/details/7601067 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:static_cast<> reinterpret_cast<>揭密
下一篇:《C++沉思录》第5章 代理类——(整理)

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月08日 20时56分10秒