gdb调试多线程

858 阅读2分钟

gdb调试多线程

线程的查看

首先创建两个线程:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
 
void* pthread_run1(void* arg)
{
    (void)arg;
 
    while(1)
    {
        printf("I am thread1,ID: %d\n",pthread_self());
        sleep(1);
    }
}
 
void* pthread_run2(void* arg)
{
    (void)arg;
 
    while(1)
    {
        printf("I am thread2,ID: %d\n",pthread_self());
        sleep(1);
    }
}
 
 
int main()
{
 
    pthread_t tid1;
    pthread_t tid2;
 
    pthread_create(&tid1,NULL,pthread_run1,NULL);
    pthread_create(&tid2,NULL,pthread_run2,NULL);
 
    printf("I am main thread\n");
 
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    return 0;
}

分析:上面程序中创建了两个线程,程序执行起来,main函数所在程序为主线程,在这个主线程中有两个新线程运行

命令行查看:

//查看当前运行的进程
ps aux|grep a.out
//查看当前运行的轻量级进程
ps -aL|grep a.out
//查看主线程和新线程的关系
pstree -p 主线程id

image.png

线程栈结构查看

  1. 获取线程ID
  2. 通过命令查看栈结构 ps stack 线程ID

image.png

利用gdb查看线程信息

将进程附加到gdb调试器当中,查看是否创建了新线程:gdb attach 主线程ID

image.png 查看线程的一些信息

//1.查看进程:info inferiors
//2.查看线程:info threads
//3.查看线程栈结构:bt
//4.切换线程:thread n(n代表第几个线程)

image.png

利用gdb调试多线程

当程序没有启动,线程还没有执行,此时利用gdb调试多线程和调试普通程序一样,通过设置断点,运行,查看信息等等,在这里不在演示,最后会加上调试线程的命令

设置断点

//1. 设置断点:break 行号/函数名
//2. 查看断点:info b

image.png

执行线程2的函数,指行完毕继续运行到断点处

1. 继续使某一线程运行:thread apply 1-n(第几个线程) n
2. 重新启动程序运行到断点处:r

image.png 只运行当前线程

1. 设置:set scheduler-locking on
2. 运行:n

image.png 所有线程并发执行

1. 设置:set scheduler-locking off
2. 运行:n

image.png

总结调试多线程的命令

image.png