lock_guard(自动加锁, 自动解锁, 读取失败就一直等待)
lock_guard<mutex> lgd(g_mutex);
unique_lock(自动加锁, 自动解锁, 根据块语句锁定)
unique_lock<mutex> ulk(g_mutex);
完整代码
#include<thread> #include<iostream> #include<mutex> using namespace std; #define N 10000000 mutex g_mutex; void add(int *p) { for(int i = 0; i < N; i++) { //自动加锁, 自动解锁, 根据块语句锁定 unique_lock<mutex> ulk(g_mutex); //根据Mutex属性, 是否可以加锁 //lock_guard<mutex> lgd(g_mutex); // //自动加锁自动解锁 //读取失败的情况就一直等待 (*p)++; } } int main() { int a = 0; thread t1(add, &a); thread t2(add, &a); t1.join(); t2.join(); std::cout << a << std::endl; cin.get(); }