#include <thread> 2 #include <iostream> 3 #include <mutex> 4 using namespace std; 5 mutex _mutex1; 6 mutex _mutex2; 7 int date1; 8 int date2; 9 int do_work_1() 10 { 11 cout << "thread_1 start" << endl; 12 lock_guard<mutex> locker1(_mutex1); 13 date1++; 14 this_thread::sleep_for(chrono::seconds(1)); 15 lock_guard<mutex> locker2(_mutex2); 16 date2++; 17 cout << "thread_1 end" << endl; 18 return 0; 19 } 20 int do_work_2() 21 { 22 cout << "thread_2 start" << endl; 23 lock_guard<mutex> locker2(_mutex2); date2++; 25 this_thread::sleep_for(chrono::seconds(1)); 26 lock_guard<mutex> locker1(_mutex1); 27 date1++; 28 cout << "thread_2 end" << endl; 29 return 0; 30 } 31 int main() 32 { 33 thread t1(do_work_1); 34 thread t2(do_work_2); 35 t1.join(); 36 t2.join(); 37 cout << "end" << endl; 38 return 0; 39 40 }
写了一个多线程死锁的程序,在linux下
(1)g++ -Wall -g -o test mutex.cpp -lpthread
(2) gdb test
(3) 执行r
产生死锁
(4) 按下ctrl + C 使程序中断
查看当前主线程的栈帧(bt)
查看栈帧2停的位置
初步判断是产生了死锁,因为join没有执行。
查看一下当前的线程,转换一下线程,查看对应的栈帧。
查看到线程2 卡在locker2上,就可以判断产生了死锁