gdb 调试多线程

以boost thread为例:

 1 #include <boost/thread.hpp>
 2 #include <iostream>
 3 
 4 void wait(int seconds) {
 5   boost::this_thread::sleep(boost::posix_time::seconds(seconds));
 6 }
 7 
 8 void thread1() {
 9   while (1) {
10     wait(1);
11     std::cout << boost::this_thread::get_id() << std::endl; 
12   }
13 }
14 
15 void thread2() {
16   while (1) {
17     wait(1);
18     std::cout << boost::this_thread::get_id() << std::endl; 
19   }
20 }
21 
22 int main() {
23   boost::thread t1(thread1);
24   boost::thread t2(thread2);
25   t1.join();
26   t2.join();
27   return 1;
28 }

使用gdb进行编译:g++ -std=c++11 -g -Wall -I/usr/local/boost/include testThread.cpp -L/usr/local/boost/lib -lboost_system -lboost_thread -o testThread (其中boost库的头文件路径和库路径为安装boost所在路径)

1. 首先使用ps命令查看线程及线程间关系

ps aux | grep testThread  查看当前运行的线程

ps -aL | grep testThread 查看当前运行的轻量级线程

pstree -p 主线程id 查看主线程和新线程之间的关系

pstack 线程id 查看线程的线程栈结构

以下为上面代码的测试结果:

查看主线程堆栈:

查看新线程堆栈:

 

2. gdb调试多线程

gdb attach 主线程id

info 查看进程和线程信息,info inferiors查看进程,info threads查看所有线程,*为当前线程,thread n切换到第n个线程,bt查看线程栈结构。

只运行当前线程: set scheduler-locking on 和所有线程并发运行: set scheduler-locking off

切换到某一线程时,实际调试过程和普通的调试程序一样,用break添加断点,n进行下一步。

3. 调试多线程的命令总结如下:

命令 用法
info threads 显示当前可调试的所有线程,每个线程会有一个GDB为其分配的ID,后面操作线程的时候会用到这个ID。 前面有*的是当前调试的线程
thread ID(1,2,3…) 切换当前调试的线程为指定ID的线程
break testThread.cpp:5 thread all(例:在相应函数的位置设置断点break wait) 在所有线程中相应的行上设置断点
thread apply ID1 ID2 command 让一个或者多个线程执行GDB命令command
thread apply all command 让所有被调试线程执行GDB命令command
set scheduler-locking 选项 command 设置线程是以什么方式来执行命令
set scheduler-locking off 不锁定任何线程,也就是所有线程都执行,这是默认值
set scheduler-locking on 只有当前被调试程序会执行
set scheduler-locking on step 在单步的时候,除了next过一个函数的情况(熟悉情况的人可能知道,这其实是一个设置断点然后continue的行为)以外,只有当前线程会执行
posted @ 2019-05-05 17:45  c++11  阅读(4484)  评论(0编辑  收藏  举报