用valgrind的helgrind工具。
先安装valgrind:
sudo apt-get install valgrind
这里故意搞个有死锁的c++程序试试看:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx1, mtx2;
void threadFunction1() {
std::lock_guard<std::mutex> lock1(mtx1); // 线程1首先锁定mtx1
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟一些工作
std::lock_guard<std::mutex> lock2(mtx2); // 然后尝试锁定mtx2
std::cout << "Thread 1: Both locks acquired\n";
}
void threadFunction2() {
std::lock_guard<std::mutex> lock2(mtx2); // 线程2首先锁定mtx2
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟一些工作
std::lock_guard<std::mutex> lock1(mtx1); // 然后尝试锁定mtx1
std::cout << "Thread 2: Both locks acquired\n";
}
int main() {
std::thread t1(threadFunction1);
std::thread t2(threadFunction2);
t1.join();
t2.join();
return 0;
}
然后编译他,记得编译的时候好+g:
g++ test1.cpp -o test1 -lpthread -g
然后进入调试:
valgrind --tool=helgrind ./test1
这里会说出,哪儿哪儿他创建了线程,退出的时候,哪个线程拿住了lock,通过什么方式拿的,在第几行。当然你得用-g来编译,如果不是debug模式的话,也会有信息,只是不会指定说在cpp的几行,但能够知道在哪个函数内发生