如何使用gdb调试死锁问题

测试代码如下:

#include <iostream>

#include <thread>

#include <mutex>

using namespace std;

mutex mtx1, mtx2;

void thread_func1() {

    unique_lock<mutex> lock(mtx1);

    for (int i = 0; i < 10; i++) {

        this_thread::sleep_for(chrono::seconds(1));

    }

    unique_lock<mutex> lock2(mtx2);

    for (int i = 0; i < 10; i++) {

        this_thread::sleep_for(chrono::seconds(1));

    }

}

void thread_func2() {

    unique_lock<mutex> lock(mtx2);

    for (int i = 0; i < 10; i++) {

        this_thread::sleep_for(chrono::seconds(1));

    }

    unique_lock<mutex> lock2(mtx1);

    for (int i = 0; i < 10; i++) {

        this_thread::sleep_for(chrono::seconds(1));

    }

}

int main(){

    cout<<"begin"<<endl;

    thread td1(thread_func1);

    thread td2(thread_func2);

    td1.join();

    td2.join();

    cout<<"done"<<endl;

    return 0;

}

启动进程后,只打印begin,没有打印done,发生了死锁现场。下面是调查方法:

1、gdb -p pid 附加到该进程

2、然后执行info threads,找到futex_wait的线程,会显示正在等待的互斥量mtx1和mtx2,和互斥量的地址

3、选择一个futex_wait的线程,打印互斥量的详细信息, p *((pthread_mutex_t *)0x5634ec6081a0) ,owner表示当前拥有该互斥量的线程的LWP值

4、然后进入owner对应的线程,查看一下堆栈,看看调用了什么函数。

5、检查futex_wait线程的当前调用函数和owner的当前调用函数,检查一下是不是存在互相等待的情况,然后改进代码。

以上是个人见解,如有问题,请大佬们斧正。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值