Boost.mutex递归访问同一把锁造成死锁

mutex虽然可以很好地协调线程同步,互斥访问全局变量。但不慎使用,也可能会造成死锁。

下面这段代码就演示了递归访问同一把锁造成的死锁:

#include<iostream>
#include<iomanip>
using namespace std;

#include <boost/thread.hpp>  
#include <boost/bind.hpp>  
#include <boost/thread/mutex.hpp>  
using namespace boost;

typedef boost::mutex CMutex;
typedef boost::lock_guard<CMutex> CLockGuardMutex;
typedef boost::thread_group CThreadGroup;


CMutex oMutexGlob;//一把全局锁,千军万马来相见

void Func1(void){
	cout << "Enter Func1" << endl;
	CLockGuardMutex oLockGuard(oMutexGlob);
	cout << "Leave Func1" << endl;
}
void Func2(void){
	cout << "Enter Func2" << endl;
	CLockGuardMutex oLockGuard(oMutexGlob);
	cout << "Leave Func2" << endl;

	Func1();//递归访问同一把锁造成死锁
}

void Run(int threadno){
	static CMutex oMutexConsole;//不能共享输出,互斥访问控制台
	CLockGuardMutex oLockGuard(oMutexConsole);
	cout << "This is Thread" << threadno << endl;

	Func2();
}

void main()
{
	CThreadGroup oThreadGroup;//定义一个线程组对象
	//创建线程
	for(int i = 0; i < 5; i++)		oThreadGroup.create_thread(boost::bind(Run, i));
	//等待所有线程退出
	oThreadGroup.join_all();
}

解决方案:使用boost::recursive_mutex【相当于Windows下的CS关键段,同一线程可以多次进入】。当同一个线程调用时,碰到相同已经上锁的锁时,还是可以继续往下执行。

#include<ctime>
#include<cstdio>
#include<iostream>
using namespace std;

#include <boost/thread.hpp>  
#include <boost/bind.hpp>  
#include <boost/thread/mutex.hpp>  
using namespace boost;

typedef boost::mutex CMutex;
typedef boost::lock_guard<CMutex> CLockGuardMutex;
typedef boost::thread_group CThreadGroup;


CMutex oMutexGlob;//一把全局锁,千军万马来相见

typedef boost::recursive_mutex CRecursiveMutex;
typedef boost::lock_guard<CRecursiveMutex> CLockGuardRecursiveMutex;

//【相当于Windows下的CS关键段,同一线程可以多次进入】
//当同一个线程调用时,碰到相同已经上锁的锁时,还是可以继续往下执行
CRecursiveMutex oRecursiveMutexGlob;

void Func1(void){
	cout << "Enter Func1" << endl;
	this_thread::sleep(posix_time::seconds(rand()%3));
	//CLockGuardMutex oLockGuard(oMutexGlob);
	CLockGuardRecursiveMutex oLockGuardRecursiveMutex(oRecursiveMutexGlob);
	cout << "Leave Func1" << endl;
}
void Func2(void){
	cout << "Enter Func2" << endl;
	//CLockGuardMutex oLockGuard(oMutexGlob);
	CLockGuardRecursiveMutex oLockGuardRecursiveMutex(oRecursiveMutexGlob);
	cout << "Leave Func2" << endl;

	Func1();//递归访问同一把锁造成死锁
}

void Run(int threadno){
	static CMutex oMutexConsole;//不能共享输出,互斥访问控制台
	CLockGuardMutex oLockGuard(oMutexConsole);
	cout << "This is Thread" << threadno << endl;

	Func2();
}

void main()
{
	srand((unsigned)time(NULL));//设置随机数的种子

	CThreadGroup oThreadGroup;//定义一个线程组对象
	//创建线程
	for(int i = 0; i < 5; i++)		oThreadGroup.create_thread(boost::bind(Run, i));
	//等待所有线程退出
	oThreadGroup.join_all();
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值