之前我们叙述过如何用gdb调试多进程,现在来讲讲如何用gdb调试多线程。
首先先要了解gdb调试多线程的基本命令:
Tables | Are |
---|---|
info threads | 显示当前可调试的所有线程,GDB会给每一个线程都分配一个ID。 |
前面有*的线程是当前正在调试的线程。 | |
thread ID | 切换当前调试的线程为指定ID的线程。 |
thread apply all command | 让所有被调试的线程都执行command命令。 |
thread apply ID1 ID2 … command | 让线程编号是ID1,ID2…等等的线程都执行command命令。 |
set scheduler-locking off/on/step | 在使用step或continue命令调试当前被调试线程的时候,其他线程也是同时执行的,如果我们只想要被调试的线程执行,而其他线程停止等待,那就要锁定要调试的线程,只让他运行。 |
off | 不锁定任何线程,所有线程都执行。 |
on | 只有当前被调试的线程会执行。 |
step | 阻止其他线程在当前线程单步调试的时候抢占当前线程。只有当next、continue、util以及finish的时候,其他线程才会获得重新运行的 |
show scheduler-locking | 查看当前锁定线程的模式。 |
举例说明:
首先编写一个比较简单的测试代码:
#include <stdio.h>
#include <pthread.h>
void *thread_1(void* arg)
{
char* msg=(char*)arg;
printf("i am %s\n",msg);
}
int main()
{
printf("i am main thread:%lu\n",pthread_self());
pthread_t id1;
pthread_create(&id1,NULL,thread_1,(void**)"thread 1");
pthread_join(id1,NULL);
return 0;
}
用gdb调试:
set scheduler-locking on:锁定其他线程,只有当前进程执行。
show scheduler-locking:查看当前锁定线程的模式。
(必须在执行状态下)
查看所有线程:
info threads:带*表示正在执行的线程
切换线程:
thread n:
下面来完整调试代码: