boost::mutex vs boost::recursive_mutex
来源:互联网 发布:node.js文档 编辑:程序博客网 时间:2024/05/19 03:25
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
- boost::mutex vs boost::recursive_mutex
- boost::mutex vs boost::recursive_mutex
- boost::mutex vs boost::recursive_mutex
- boost::mutex vs boost::recursive_mutex
- boost::mutex vs boost::recursive_mutex
- Boost - 多线程-boost recursive_mutex用法
- Boost - 多线程-boost recursive_mutex用法
- boost::recursive_mutex::scoped_lock
- boost mutex
- boost Mutex
- boost递归锁recursive_mutex 测试
- 【原创】boost::recursive_mutex请小心使用
- boost mutex condition
- boost::thread mutex
- (Boost)mutex scoped_lock
- boost::mutex::scoped_lock
- boost mutex lock 使用
- boost::unique_lock vs boost::lock_guard
- 几何-点的构建(python版)
- Cocoa: NSTableView与NSTableDataSource
- magento -- 使用local.xml来修改布局
- 算法复杂度的计算
- Return to the Basic - 复制构造函数. (Copy Constructor )
- boost::mutex vs boost::recursive_mutex
- listview控件使用
- 计算任意Mesh的切线空间向量
- NPOI生成Excel
- 在oracle DB 中汉字不一定是占两个字符
- linux中Shell历史命令记录文件的路径是什么
- 黑马程序员——反射
- Mac OS环境下媒体文件分割工具mediafilesegmenter的简单使用
- spring (使用@autowired注解)