boost::mutex vs boost::recursive_mutex
来源:互联网 发布:公司注销,淘宝企业店铺 编辑:程序博客网 时间:2024/05/25 23:57
boost::mutex vs boost::recursive_mutex
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
- 物理渲染-基于物理的光照模型
- Hdoj 1179 Ollivanders: Makers of Fine Wands since 382 BC. 【二分匹配】
- Search a 2D Matrix
- 浅谈 -128的原码 反码 补码
- 顺序容器:容器的赋值、swap、assign
- boost::mutex vs boost::recursive_mutex
- 从java一道多线程题目想到
- 我终于变成了一个喜欢自己的姑娘(有效地改变自己)
- C语言 a++为什么不能作为左值?
- DataSet、DataTable、DataRow、DataColumn区别及使用实例
- 2015-第3周项目4-考了语文数学的学生
- hdoj 2391 Filthy Rich (动态规划)
- zlog成功移植到OK6410 上来
- Android应用中调用输入法后界面调整问题的解决