C++模拟产生死锁

产生死锁的条件是需要两把锁,两个线程各自持有其中的一把,在没有释放的前提下申请另一把。

模拟代码如下:

/**
 * Created by fangruibin
 * 测试死锁产生的场景
 */

#include <iostream>
#include <pthread.h>
#include <unistd.h>

//定义两把锁
pthread_mutex_t m_mutex1;
pthread_mutex_t m_mutex2;
int A = 0, B = 0;

//线程1
void* threadFunc1(void* p)
{
	//printf("thread 1 running..\n");
	pthread_mutex_lock(&m_mutex1);
	A = 1;
	printf("thread 1 write source A\n");
	usleep(100);
	
	pthread_mutex_lock(&m_mutex2);
	B = 1;
	printf("thread 1 write source B\n");
	
	//解锁,实际上是跑不到这里的,因为前面已经死锁了
	pthread_mutex_unlock(&m_mutex2);
	pthread_mutex_unlock(&m_mutex1);
	
	return NULL;
}

//线程2
void* threadFunc2(void* p)
{
	//printf("thread 2 running..\n");
	pthread_mutex_lock(&m_mutex2);
	B = 1;
	printf("thread 2 write source B\n");
	usleep(100);
	
	pthread_mutex_lock(&m_mutex1);
	A = 1;
	printf("thread 2 write source A\n");
	
	//解锁,实际上是跑不到这里的,因为前面已经死锁了
	pthread_mutex_unlock(&m_mutex1);
	pthread_mutex_unlock(&m_mutex2);
	
	return NULL;
}

int main()
{
	//初始化锁
	if (pthread_mutex_init(&m_mutex1, 0) != 0)
	{
		printf("init mutex 1 failed\n");
		return -1;
	}
	if (pthread_mutex_init(&m_mutex2, 0) != 0)
	{
		printf("init mutex 2 failed\n");
		return -1;
	}
	
	//初始化线程
	pthread_t hThread1;
	pthread_t hThread2;
	if (pthread_create(&hThread1, NULL, &threadFunc1, NULL) != 0)
	{
		printf("create thread 1 failed\n");
		return -1;
	}
	if (pthread_create(&hThread2, NULL, &threadFunc2, NULL) != 0)
	{
		printf("create thread 2 failed\n");
		return -1;
	}
	
	while (1)
	{
		sleep(1);
	}
	
	pthread_mutex_destroy(&m_mutex1);
	pthread_mutex_destroy(&m_mutex2);
	return 0;
}

编译:

gcc deadlock.cpp -lpthread -o deadlock

没有死锁情况下应该输出如下(先后顺序可能不是这样):

thread 1 write source A
thread 1 write source B
thread 2 write source A
thread 2 write source B

实际输出结果:

thread 2 write source B
thread 1 write source A

由于产生死锁,后面的内容无法输出。

另一种死锁情况——读锁重入

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值