用g++进行编译时候要加上-g标签g++ -std=c++11 -g 2.cpp -o 2 -pthread
方法一:运行程序->找到pid->使用pid进入gdb调试
- 运行程序,发现程序锁死,使用ps找到程序的pid:
ps -aux | grep ./app 其中./app为程序名
- 执行
gdb -p pid
进入gdb调试界面 - 执行
i threads
打印当前所有线程
(gdb) i threads
Id Target Id Frame
1 Thread 0x7f9082d44740 (LWP 7940) "2" 0x00007f908239198d in pthread_join (threadid=140258629605120, thread_return=0x0) at pthread_join.c:90
* 2 Thread 0x7f9081cb5700 (LWP 7941) "2" __lll_lock_wait () at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:135
3 Thread 0x7f90814b4700 (LWP 7942) "2" __lll_lock_wait () at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:135
- 执行
thread 2
进入线程2,执行bt
打印堆栈信息,可以定位到第五行in do_work_1 () at 2.cpp:15
(gdb) bt
#0 __lll_lock_wait () at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:135
#1 0x00007f9082392dbd in __GI___pthread_mutex_lock (mutex=0x605320 <_mutex2>) at ../nptl/pthread_mutex_lock.c:80
#2 0x0000000000401047 in __gthread_mutex_lock (__mutex=0x605320 <_mutex2>) at /usr/include/x86_64-linux-gnu/c++/5/bits/gthr-default.h:748
#3 0x000000000040173e in std::mutex::lock (this=0x605320 <_mutex2>) at /usr/include/c++/5/mutex:135
#4 0x00000000004017e4 in std::lock_guard<std::mutex>::lock_guard (this=0x7f9081cb4e50, __m=...) at /usr/include/c++/5/mutex:386
#5 0x0000000000401191 in do_work_1 () at 2.cpp:15
#6 0x0000000000402d69 in std::_Bind_simple<int (*())()>::_M_invoke<>(std::_Index_tuple<>) (this=0x1449c48) at /usr/include/c++/5/functional:1531
#7 0x0000000000402cc2 in std::_Bind_simple<int (*())()>::operator()() (this=0x1449c48) at /usr/include/c++/5/functional:1520
#8 0x0000000000402c52 in std::thread::_Impl<std::_Bind_simple<int (*())()> >::_M_run() (this=0x1449c30) at /usr/include/c++/5/thread:115
#9 0x00007f9082874c80 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#10 0x00007f90823906ba in start_thread (arg=0x7f9081cb5700) at pthread_create.c:333
方法二:直接使用gdb打开程序->run运行->出现死锁->ctrl+c关闭,之后同上
- 载入程序
sudo gdb ./2
- 运行
run
- ctrl+c关闭程序,之后同上。