//防止同一片内存被同时修改
#include <iostream>
#include<thread>
#include<vector>
#include<algorithm>
#include<functional>
#include<mutex>
using namespace std;
struct A
{
int a;
};
std::mutex _mutex;
void func_add(A& a )
{
cout <<"add func a has address:" <<&a << endl;
for (int i = 0; i < 100000; i++)
{
std::lock_guard<std::mutex> guard(_mutex);
a.a++;
}
cout << "from add func: " << a.a << endl;
}
//这里有必要传递 引用或指针
void func_sub(A& a)
{
cout << "sub func a has address:" << &a << endl;
for (int i = 0; i < 100000; i++)
{
std::lock_guard<std::mutex> guard(_mutex);
a.a--;
}
cout << "from sub func: " << a.a << endl;
}
int main()
{
A a;
a.a = 0;
thread t_add(func_add, ref(a));
thread t_sub(func_sub, ref(a));
t_sub.join();
t_add.join();
cout << "from main func :"<< a.a<<endl;
}
C++ mutex使用
最新推荐文章于 2024-06-17 18:56:48 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)