当多个函数操作同一个锁时,锁住一个变量时要尽快解锁,不要同时锁住一个相同的变量,这时就容易发生死锁的情况
// // Created by Administrator on 2021/7/2. // #include<iostream> #include<mutex> #include<thread> using namespace std; //thread引用类型函数,模板,避免类型转换,尽量指针 //锁住一个变量以后,要尽快解锁,不要锁住其他变量 #define COUNT 1000000 mutex g_mutex1, g_mutex2; //互斥量 void add1(int *p1, int *p2) { for(int i = 0; i < COUNT; ++i) { // g_mutex1.lock(); // g_mutex2.unlock(); // (*p1)++; // g_mutex2.unlock(); // g_mutex1.lock(); // (*p2)++; g_mutex1.lock(); (*p1)++; g_mutex1.unlock(); g_mutex2.lock(); (*p2)++; g_mutex2.unlock(); } } void add2(int *p1, int *p2) { for(int i = 0; i < COUNT; ++i) { // g_mutex2.lock(); // g_mutex1.unlock(); // (*p1)++; // g_mutex1.unlock(); // g_mutex2.lock(); // (*p2)++; g_mutex2.lock(); (*p2)++; //计算完解锁 g_mutex2.unlock(); g_mutex1.lock(); (*p1)++; g_mutex1.unlock(); } } int main() { int a = 0; int b = 0; thread th1(add1, &a, &b); thread th2(add2, &a, &b); th1.join(); th2.join(); while(1) { cout << a << endl; cout << a << endl; this_thread::sleep_for(chrono::seconds(3)); } // th1.join(); // th2.join(); cout << a << endl; cout << a << endl; cin.get(); }