使用 gdb 调试死锁线程

死锁调试预备

  • -g 参数
  • attach
  • info threads
  • thread + number 切换对应线程

testlock.cpp

  1 #include 
  2 #include 
  3 #include 
  4 #include 
  5 
  6 std::mutex gMutex;
  7 
  8 void Test1()
  9 {   
 10     gMutex.lock();
 11     gMutex.lock();
 12 }
 13 
 14 void Test2()
 15 {   
 16     while (true) {
 17         sleep(1);
 18     }
 19 }
 20 
 21 int main()
 22 {   
 23     std::thread t1(Test1);
 24     std::thread t2(Test2);
 25     
 26     t1.join();
 27     t2.join();
 28     return 0;
 29 }

编译运行
编译:$ g++ -std=c++11 -g ./testlock.cpp -pthread
运行:$ ./a.out
程序挂起,然后使用 gdb 进行调试。

gdb 调试

# 查找进程 id
$ ps -ef |grep a.out
test 18951 18823  0 17:26 pts/7 00:00:00  ./a.out

# 使用 root 权限 进入 attach
$ gdb a.out 18951
(gdb) info threads
  Id   Target Id         Frame 
* 1    Thread 0x7f4545f6a740 (LWP 18951) "a.out" 0x00007f45455a798d in pthread_join (threadid=139935485835008, thread_return=0x0)
    at pthread_join.c:90
  2    Thread 0x7f4544ecb700 (LWP 18952) "a.out" __lll_lock_wait () at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:135
  3    Thread 0x7f45446ca700 (LWP 18953) "a.out" 0x00007f45452a130d in nanosleep () at ../sysdeps/unix/syscall-template.S:84

# 调到第二个线程
(gdb)t 2
[Switching to thread 2 (Thread 0x7f4544ecb700 (LWP 18952))]
#0  __lll_lock_wait () at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:135
135     ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S: 没有那个文件或目录.

# 执行 bt
(gdb) bt
#0  __lll_lock_wait () at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:135
#1  0x00007f45455a8dbd in __GI___pthread_mutex_lock (mutex=0x6041a0 ) at ../nptl/pthread_mutex_lock.c:80
#2  0x0000000000400e67 in __gthread_mutex_lock (__mutex=0x6041a0 ) at /usr/include/x86_64-linux-gnu/c++/5/bits/gthr-default.h:748
#3  0x0000000000401224 in std::mutex::lock (this=0x6041a0 ) at /usr/include/c++/5/mutex:135
#4  0x0000000000400f0f in Test1 () at ./testlock.cpp:11
#5  0x0000000000402525 in std::_Bind_simple::_M_invoke<>(std::_Index_tuple<>) (this=0x1b77c48)
    at /usr/include/c++/5/functional:1531
#6  0x000000000040247e in std::_Bind_simple::operator()() (this=0x1b77c48) at /usr/include/c++/5/functional:1520
#7  0x000000000040240e in std::thread::_Impl >::_M_run() (this=0x1b77c30) at /usr/include/c++/5/thread:115
#8  0x00007f4545a8ac80 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#9  0x00007f45455a66ba in start_thread (arg=0x7f4544ecb700) at pthread_create.c:333
#10 0x00007f45452dc3dd in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:109

可以看到第 4 项 #4 0x0000000000400f0f in Test1 () at ./testlock.cpp:11 程序卡在了文件的 11 行。

你可能感兴趣的:(使用 gdb 调试死锁线程)