gdb多线程调试
gdb提供的多线程调试工具
- 新线程创建自动提醒
thread thread-id
实现不同线程之间的切换info threads
查询存在的线程thread apply [thread-id-list] [all] args
在一系列线程上执行命令- 线程中设置指定的断点
set print thread-events
控制打印线程启动或结束是的信息set scheduler-locking off|on|step
在使用step或是continue进行调试的时候,其他可能也会并行的执行,如何才能够只让被调试的线程执行呢?该命令工具可以达到这个效果。off:不锁定任何线程,也就是所有的线程都执行,这是默认值。
on:只有当前被调试的线程能够执行。
step:阻止其他线程在当前线程单步调试时,抢占当前线程。只有当next、continue、util以及finish的时候,其他线程才会获得重新运行的机会。
示例代码
#include <iostream>
#include <pthread.h>
#include <iostream>
void* threadPrintHello(void* arg)
{
while(1)
{
sleep(5);
std::cout << "hello" << std::endl;
}
}
void* threadPrintWorld(void* arg)
{
while(1)
{
sleep(5);
std::cout << "world" << std::endl;
}
}
int main( int argc , char* argv[])
{
pthread_t pid_hello , pid_world;
int ret = 0;
ret = pthread_create(&pid_hello , NULL , threadPrintHello , NULL);
if( ret != 0 )
{
std::cout << "Create threadHello error" << std::endl;
return -1;
}
ret = pthread_create(&pid_world , NULL , threadPrintWorld , NULL);
if( ret != 0 )
{
std::cout << "Create threadWorld error" << std::endl;
return -1;
}
while(1)
{
sleep(10);
std::cout << "In main thread" << std::endl;
}
pthread_join(pid_hello , NULL);
pthread_join(pid_world , NULL);
return 0;
}
线程创建提醒
在GNU/Linux上,如果gdb检测一个新的线程,会给出如下通知
[New Thread 0x7ffff708b700 (LWP 20567)]
[New Thread 0x7ffff688a700 (LWP 20568)]
查询已经存在的线程
使用info threads可以看到程序中所有线程的信息
(gdb) info threads
3 Thread 0x7ffff688a700 (LWP 20568) 0x00007ffff70be8e0 in sigprocmask () from /lib64/libc.so.6
2 Thread 0x7ffff708b700 (LWP 20567) 0x00007ffff7138a3d in nanosleep () from /lib64/libc.so.6
* 1 Thread 0x7ffff7fe5720 (LWP 20564) main (argc=1, argv=0x7fffffffe628) at multithreads.cpp:39
主要包括gdb分配的线程id号(例如1,2,3),操作系统分配的线程id(例如20568),线程的名字以及线程相关的调用栈信息。
切换线程
thread threadno可以切换到指定的线程,threadno就是上面gdb分配的线程id号。
(gdb) thread 2
[Switching to thread 2 (Thread 0x7ffff708b700 (LWP 20567))]#0 0x00007ffff7138a3d in nanosleep () from /lib64/libc.so.6
锁定一个线程
默认情况下gdb不锁定任何线程</