使用GDB打印线程层次结构

时间:2014-08-05 14:36:46

标签: multithreading gdb

我有一个多线程程序,我试图调试。当我在GDB中运行info thread时,我得到以下内容:

(gdb) info thread
  Id   Target Id         Frame 
  8    Thread 0x7fffe77fd700 (LWP 17425) "SocketWriter" 0x00007ffff7bc9b2f in pthread_cond_wait@@GLIBC_2.3.2 () from /usr/lib/libpthread.so.0
  7    Thread 0x7fffe73fc700 (LWP 17426) "SocketWriter" 0x00007ffff7bc9b2f in pthread_cond_wait@@GLIBC_2.3.2 () from /usr/lib/libpthread.so.0
  6    Thread 0x7fffe7fff700 (LWP 17423) "SocketReader" 0x00007ffff7bcc66d in read () from /usr/lib/libpthread.so.0
  5    Thread 0x7fffe7bfe700 (LWP 17424) "SocketReader" 0x00007ffff7bcc66d in read () from /usr/lib/libpthread.so.0
* 4    Thread 0x7ffff4810700 (LWP 17422) "unittest" 0x00007ffff7bcc38c in __lll_lock_wait () from /usr/lib/libpthread.so.0
  3    Thread 0x7ffff4c11700 (LWP 17421) "receiver" 0x00007ffff7bcc38c in __lll_lock_wait () from /usr/lib/libpthread.so.0
  2    Thread 0x7ffff5a3b700 (LWP 17420) "unittest" 0x00007ffff634e553 in select () from /usr/lib/libc.so.6
  1    Thread 0x7ffff7fc9780 (LWP 17419) "unittest" 0x00007ffff7bc9b2f in pthread_cond_wait@@GLIBC_2.3.2 () from /usr/lib/libpthread.so.0

如果我能让GDB显示线程之间的父/子关系,那将是非常好的,如下所示:

(gdb) info thread
  Id   Target Id         Frame 
  1    Thread 0x7ffff7fc9780 (LWP 17419) "unittest" 0x00007ffff7bc9b2f in pthread_cond_wait@@GLIBC_2.3.2 () from /usr/lib/libpthread.so.0
    3    Thread 0x7ffff4c11700 (LWP 17421) "receiver" 0x00007ffff7bcc38c in __lll_lock_wait () from /usr/lib/libpthread.so.0
      8    Thread 0x7fffe77fd700 (LWP 17425) "SocketWriter" 0x00007ffff7bc9b2f in pthread_cond_wait@@GLIBC_2.3.2 () from /usr/lib/libpthread.so.0
      6    Thread 0x7fffe7fff700 (LWP 17423) "SocketReader" 0x00007ffff7bcc66d in read () from /usr/lib/libpthread.so.0
      2    Thread 0x7ffff5a3b700 (LWP 17420) "unittest" 0x00007ffff634e553 in select () from /usr/lib/libc.so.6
    5    Thread 0x7fffe7bfe700 (LWP 17424) "SocketReader" 0x00007ffff7bcc66d in read () from /usr/lib/libpthread.so.0
*   4    Thread 0x7ffff4810700 (LWP 17422) "unittest" 0x00007ffff7bcc38c in __lll_lock_wait () from /usr/lib/libpthread.so.0
    7    Thread 0x7fffe73fc700 (LWP 17426) "SocketWriter" 0x00007ffff7bc9b2f in pthread_cond_wait@@GLIBC_2.3.2 () from /usr/lib/libpthread.so.0

例如,线程3是线程8,6和2的父线程,线程1是所有线程的父线程。

是否存在此类功能?如果有的话,我还没有看到它的引用。

1 个答案:

答案 0 :(得分:4)

gdb不打印此信息,因为它在您的程序中不存在 - 一旦创建了线程,gdb就无法发现它。

可能有两种方法可以做到。

首先,您可以在线程创建功能上设置断点并记录信息。这很容易从Python完成。然后你也可以用Python编写一个新的命令来按你喜欢的方式格式化输出。

这种方法的问题在于,如果您“附加”到正在运行的程序,它将无法工作。捕获信息为时已晚。

另一种方法是,如果您的程序中有可用的额外信息来描述层次结构。然后,您可以在Python中编写一个新命令,提取此信息以显示您喜欢的内容。