> 文章列表 > gdb多线程调试

gdb多线程调试

gdb多线程调试

gdb多线程调试
1.背景
采用gdb调试代码时,经常遇到多线程的情况,但对gdb在多线程中的切换并不熟悉,导致排查问题很困难,所以整理下多线程调试方法。
2.gdb多线程调试指令及简介
调试代码时先将代码跑起来,然后ctrl+c将代码中断。
bt打印出堆栈时,f 栈编号 可以直接执行该函数
查看线程信息:i threads [id …]
不指定id就查看所以的线程信息。
切换线程:thread id
在多个线程执行指令:thread apply all bt
锁定当前线程,暂停其它线程:set scheduler-locking on,
如果只想n或者s单步调试锁定线程时:set scheduler-locking step
取消锁定set scheduler-locking off
注意:打了断点后,执行到断点会暂停所有线程。
3.代码示例

#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
mutex lock1;
int cnt = 0;
void fun1()
{while(1){{lock_guard<mutex> l(lock1);std::cout << "callfun1 cnt:"<< cnt++ << std::endl;}std::this_thread::sleep_for(std::chrono::milliseconds(500));}
}
void fun2()
{while(1){{lock_guard<mutex> l(lock1);std::cout << "callfun2 cnt:"<< cnt++ << std::endl;}std::this_thread::sleep_for(std::chrono::milliseconds(500));}
}int main()
{thread thd1(fun1);thread thd2(fun2);thd1.join();thd2.join();cout << "thread 1 and 2 is end" << endl;return 0;
}

查看进程信息
gdb多线程调试
切换进程
gdb多线程调试
堆栈打印和进入函数
gdb多线程调试
线程锁定前效果:
gdb多线程调试
线程锁定后效果:
gdb多线程调试

参考文档:
https://github.com/hellogcc/100-gdb-tips
https://www.cnblogs.com/hellokitty2/p/16869185.html