测试代码如下:
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx1, mtx2;
void thread_func1() {
unique_lock<mutex> lock(mtx1);
for (int i = 0; i < 10; i++) {
this_thread::sleep_for(chrono::seconds(1));
}
unique_lock<mutex> lock2(mtx2);
for (int i = 0; i < 10; i++) {
this_thread::sleep_for(chrono::seconds(1));
}
}
void thread_func2() {
unique_lock<mutex> lock(mtx2);
for (int i = 0; i < 10; i++) {
this_thread::sleep_for(chrono::seconds(1));
}
unique_lock<mutex> lock2(mtx1);
for (int i = 0; i < 10; i++) {
this_thread::sleep_for(chrono::seconds(1));
}
}
int main(){
cout<<"begin"<<endl;
thread td1(thread_func1);
thread td2(thread_func2);
td1.join();
td2.join();
cout<<"done"<<endl;
return 0;
}
启动进程后,只打印begin,没有打印done,发生了死锁现场。下面是调查方法:
1、gdb -p pid 附加到该进程
2、然后执行info threads,找到futex_wait的线程,会显示正在等待的互斥量mtx1和mtx2,和互斥量的地址
3、选择一个futex_wait的线程,打印互斥量的详细信息, p *((pthread_mutex_t *)0x5634ec6081a0) ,owner表示当前拥有该互斥量的线程的LWP值
4、然后进入owner对应的线程,查看一下堆栈,看看调用了什么函数。
5、检查futex_wait线程的当前调用函数和owner的当前调用函数,检查一下是不是存在互相等待的情况,然后改进代码。
以上是个人见解,如有问题,请大佬们斧正。