gdb调试多线程

来源:互联网 发布:知乎日本都市传说 编辑:程序博客网 时间:2024/05/16 23:58

gdb的线程调试命令将在下面边调试边介绍,下面先给出示例代码:

示例代码

#include<stdio.h>#include<pthread.h>#include<unistd.h> void* pthread_run1(void* arg){       int count=5;    while(count--)    {           printf("hello world!\n");        sleep(1);    }    printf("pthread1:%lu\n",pthread_self());    pthread_exit(NULL);    return NULL;}void* pthread_run2(void* arg){    int i=0;    for(;i<5;++i)    {        printf("%d\n",i);        sleep(1);    }    printf("pthread2:%lu\n",pthread_self());    pthread_exit(NULL);     return NULL;}  int main(){    printf("main pthread:%lu\n",pthread_self());      pthread_t tid1,tid2;    pthread_create(&tid1,NULL,pthread_run1,NULL);    pthread_create(&tid2,NULL,pthread_run2,NULL);     pthread_join(tid1,NULL);    pthread_join(tid2,NULL);return 0;}                                                                          

在调试之前,我们需要注意在Makefile文件里添加的信息:


1.显示代码


2. info threads:显示当前可调式的所有线程,gdb为每一个线程分配ID,这个ID后续操作的时候进行使用。


3. thread ID :切换到当前调试的线程的指定ID


3. set scheduler-locking off|on|step:在使用step或continue命令调试当前被调试线程的时候,其他线程也是同时执行的,如果我们只想要被调试的线程执行,而其他线程停止等待,那就要锁定要调试的线程,只让它运行。 

  • off:不锁定任何线程,所有线程都执行(默认值)。 
  • on:只有当前被调试的线程会执行。 
  • step:阻止其他线程在当前线程单步调试的时候抢占当前线程。只有当next、continue、util以及finish的时候,其他线程才会获得重新运行.
(1)测试参数on

若是不锁定,则线程2退出后,单步就接着执行线程3.
(2)测试参数step
       为了达到预期测试目的,pthread_run1 函数设置有句代码执行一次sleep 一秒,在加入step参数后,调试过程中我们会发现在第一个函数处打断点并运行至第一个断点处后,单步调试后先执行函数 1 中的部分代码,在sleep期间将继续执行函数 2中的代码,下面来看看现象:



4. set print thread-events :用于设定是否提示线程启动或停止时的信息。 

5. thread apply ID command :让ID线程执行命令command。

 
6. thread apply all command :让所有线程执行命令command。


线程的调试就说到这里,熟练掌握还得在运用中多加练习!

0 0