std mutex 用对象锁住
时间: 2023-06-19 21:10:47 浏览: 49
在 C++ 中,std::mutex 是一个用于保护共享资源的同步原语。它提供了两个基本操作:lock() 和 unlock()。当一个线程调用 lock() 函数时,它将锁住互斥量并且获得对共享资源的独占访问权限。当线程完成对共享资源的访问时,它调用 unlock() 函数来释放锁。
下面是一个例子,演示了如何使用 std::mutex 来保护共享资源:
```cpp
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mutex;
int shared_data = 0;
void increment_shared_data()
{
// 锁住互斥量
mutex.lock();
// 访问共享资源
++shared_data;
// 解锁互斥量
mutex.unlock();
}
int main()
{
std::thread t1(increment_shared_data);
std::thread t2(increment_shared_data);
t1.join();
t2.join();
std::cout << "shared_data = " << shared_data << std::endl;
return 0;
}
```
在上面的例子中,两个线程 t1 和 t2 同时访问共享资源 shared_data。为了保证数据的正确性,我们使用了 std::mutex 对象 mutex 来锁住共享资源。当一个线程访问共享资源之前,它必须先锁住互斥量。只有当线程完成对共享资源的访问时,它才能将互斥量解锁,以便其他线程可以访问共享资源。这样就保证了共享资源的正确性和一致性。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)