Linux GDB分析死锁

目录

示例代码

分析

结论


示例代码

// DeadLock.cpp : 定义控制台应用程序的入口点。
//

#include <iostream>
#include <stdlib.h>
#include <thread>
#include <mutex>

static std::mutex mutex1;
static std::mutex mutex2;

static int threadFunc1()
{		
	std::cout << "Enter threadFunc1" << std::endl;
	std::lock_guard<std::mutex> lock1(mutex1);	
	std::this_thread::sleep_for(std::chrono::seconds(20));
	std::lock_guard<std::mutex> lock2(mutex2);
	std::cout << "Leave threadFunc1" << std::endl;	
	return 0;
}

static int threadFunc2()
{
	std::cout << "Enter threadFunc2" << std::endl;
	std::lock_guard<std::mutex> lock1(mutex2);		
	std::this_thread::sleep_for(std::chrono::seconds(20));	
	std::lock_guard<std::mutex> lock2(mutex1);
	std::cout << "Leave threadFunc2" << std::endl;	
	return 0;
}

int main()
{
	std::thread thread1(threadFunc1);
	std::thread thread2(threadFunc2);
	
	thread1.join();
	thread2.join();

	std::cout << "All thread end,now exit" << std::endl;	
    return 0;
}

编译运行(目标程序为testDemo):./testDemo

Enter threadFunc1

Enter threadFunc2

并未输出:Leave threadFunc1 、 Leave threadFunc2、All thread end,now exit,随后程序处于挂起状态

分析

1、Gdb调试:gdb ./testDemo

2、 待到程序无反应时,通过Ctrl+C中断程序运行

3、查看线程信息:info threads

Id   Target Id         Frame

* 1    Thread 0x7ffff7fdb740 (LWP 4315) "testDemo" 0x00007ffff7bbed2d in __GI___pthread_timedjoin_e

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值