1 #include <iostream> 2 #include <thread> 3 #include <mutex> 4 using namespace std; 5 6 #define COUNT 100000 7 8 mutex g_mutex1, g_mutex2;//互斥量 9 10 void add1(int *a, int *b) 11 { 12 for (int i = 0; i < COUNT; i++) 13 { 14 g_mutex1.lock(); 15 (*a)++; 16 17 18 g_mutex2.lock(); 19 (*b)++; 20 21 g_mutex2.unlock(); 22 g_mutex1.unlock(); 23 } 24 } 25 26 void add2(int *a, int *b) 27 { 28 for (int i = 0; i < COUNT; i++) 29 { 30 g_mutex2.lock(); 31 g_mutex1.lock(); 32 (*a)++; 33 g_mutex1.unlock(); 34 (*b)++; 35 g_mutex2.unlock(); 36 } 37 } 38 39 void main() 40 { 41 int a = 0; 42 int b = 0; 43 thread th1(add1, &a, &b); 44 thread th2(add2, &a, &b); 45 46 while (1) 47 { 48 cout << a << endl; 49 cout << b << endl; 50 this_thread::sleep_for(chrono::seconds(2)); 51 } 52 }
要想解决死锁就需要lock与unlock成对使用,不允许连续使用两个lock
1 #include <iostream> 2 #include <thread> 3 #include <mutex> 4 using namespace std; 5 6 #define COUNT 100000 7 8 mutex g_mutex1, g_mutex2;//互斥量 9 10 void add1(int *a, int *b) 11 { 12 for (int i = 0; i < COUNT; i++) 13 { 14 g_mutex1.lock(); 15 (*a)++; 16 g_mutex1.unlock(); 17 18 g_mutex2.lock(); 19 (*b)++; 20 g_mutex2.unlock(); 21 22 } 23 cout << "end" << endl; 24 } 25 26 void add2(int *a, int *b) 27 { 28 for (int i = 0; i < COUNT; i++) 29 { 30 31 g_mutex1.lock(); 32 (*a)++; 33 g_mutex1.unlock(); 34 g_mutex2.lock(); 35 (*b)++; 36 g_mutex2.unlock(); 37 38 } 39 cout << "end" << endl; 40 } 41 42 void main() 43 { 44 int a = 0; 45 int b = 0; 46 thread th1(add1, &a, &b); 47 thread th2(add2, &a, &b); 48 49 while (1) 50 { 51 cout << a << endl; 52 cout << b << endl; 53 this_thread::sleep_for(chrono::seconds(1)); 54 } 55 }