目录
调试多线程
GDB调试多线程程序常用命令
调试命令 | 功 能 |
---|---|
info threads | 查看当前调试环境中包含多少个线程,并打印出各个线程的相关信息,包括线程编号(ID)、线程名称等。 |
thread id | 将线程编号为 id 的线程设置为当前线程。 |
thread apply id… command | id… 表示线程的编号;command 代指 GDB 命令,如 next、continue 等。整个命令的功能是将 command 命令作用于指定编号的线程。当然,如果想将 command 命令作用于所有线程,id… 可以用 all 代替。 |
break location thread id | 在 location 指定的位置建立普通断点,并且该断点仅用于暂停编号为 id 的线程。 |
set scheduler-locking off|on|step | 默认情况下,当程序中某一线程暂停执行时,所有执行的线程都会暂停;同样,当执行 continue 命令时,默认所有暂停的程序都会继续执行。该命令可以打破此默认设置,即只继续执行当前线程,其它线程仍停止执行。 |
调试的代码:
#include <stdio.h>
#include <pthread.h>
void* thread_job(void*name)
{
char * thread_name = (char*)name;
printf("this is %s\n",thread_name);
sleep(2);
printf("http://c.biancheng.net\n");
}
int main()
{
pthread_t tid1,tid2;
pthread_create(&tid1, NULL, thread_job, "thread1_job");
pthread_create(&tid2, NULL, thread_job, "thread2_job");
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
printf("this is main\n");
return 0;
}
编译命令:
gcc main.c -o main -g -lpthread
查看所有线程
info threads 命令的功能有 2 个,既可以查看当前调试环境下存在的线程数以及各线程的具体信息,也可以通过指定线程的编号查看某个线程的具体信息。
(gdb) info threads [id...]
其中,参数 id… 作为可选参数,表示要查看的线程编号,编号个数可以是多个。
(gdb) b 6
Breakpoint 5 at 0x400699: file main.c, line 6.
(gdb) r
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /root/learn/c++11/main
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".