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的行为)以外,只有当前线程会执行

转载于:https://www.cnblogs.com/sssblog/p/10815184.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值