1 #include <iostream> 2 #include <thread> 3 #include <mutex> 4 using namespace std; 5 6 #define N 100000 7 8 mutex g_mutex; 9 10 void add(int *p) 11 { 12 for (int i = 0; i < N; i++) 13 { 14 //拥有mutex所有权,自动加锁自动解锁,读取失败就会一直等待 15 //lock_guard<mutex> lgd(g_mutex); 16 //unique也能加锁,但是速度比较慢,根据块语句锁定,根据mutex属性能否加锁 17 unique_lock<mutex> ulk(g_mutex); 18 (*p)++; 19 } 20 } 21 22 void main() 23 { 24 int a = 0; 25 thread t1(add, &a); 26 thread t2(add, &a); 27 t1.join(); 28 t2.join(); 29 cout << a << endl; 30 cin.get(); 31 }