gdb 调试多线程

以boost thread为例:ios

 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所在路径)c++

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

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

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

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

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

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

查看主线程堆栈:spa

查看新线程堆栈:线程

 

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的行为)之外,只有当前线程会执行
相关文章
相关标签/搜索