C++读锁重入导致死锁

我们知道使用读写锁时,多个线程可以同时申请读锁,而同个线程嵌套申请同个读锁则有可能导致死锁,应该避免这样使用。

我们假设有线程A、B和锁L,按如下时序执行:

1、线程A申请读锁L;

2、线程B申请写锁L;

3、线程A再次申请读锁L;

此时便产生了死锁!

下面是模拟死锁代码:

/**
 * Created by fangruibin
 * 测试读锁嵌套导致死锁的场景
 */

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


pthread_rwlock_t m_lock;
int A = 0, B = 0;

//线程1
void* threadFunc1(void* p)
{
  //printf("thread 1 running..\n");
  pthread_rwlock_rdlock(&m_lock);
  printf("thread 1 read source A=%d\n", A);
  usleep(100); // 等待100ms,此时线程2大概率会被唤醒并申请写锁
  
  pthread_rwlock_rdlock(&m_lock);
  printf("thread 1 read source B=%d\n", B);
  
  //释放读锁
  pthread_rwlock_unlock(&m_lock);
  pthread_rwlock_unlock(&m_lock);
  
  return NULL;
}

//线程2
void* threadFunc2(void* p)
{
  //printf("thread 2 running..\n");
  pthread_rwlock_wrlock(&m_lock);
  A = 1;
  B = 1;
  printf("thread 2 write source A and B\n");
  
  //释放写锁
  pthread_rwlock_unlock(&m_lock);
  
  return NULL;
}

int main()
{
  //初始化读写锁
  if (pthread_rwlock_init(&m_lock, 0) != 0)
  {
    printf("init rwlock 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_rwlock_destroy(&m_lock);
  return 0;
}

运行结果:

fangruibin@LP210300018 lock % ./deadlock2 
thread 1 read source A=0

可以看出,线程1只打印了一条日志便卡住了,第二条日志没打印出来;而线程2则没有任何日志输出。

建议:避免嵌套申请读锁

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值