来个std::lock_guard的使用样例
时间: 2023-05-19 20:03:28 浏览: 53
当我们需要在多个线程中访问共享资源时,需要使用互斥锁来保证线程安全。而 std::lock_guard 是一个 RAII(Resource Acquisition Is Initialization)类,它可以在构造函数中锁定互斥锁,在析构函数中解锁互斥锁,从而保证在任何情况下都能正确释放锁。
下面是一个使用 std::lock_guard 的样例:
```c++
#include <iostream>
#include <mutex>
std::mutex mtx; // 全局互斥锁
void print(int n) {
std::lock_guard<std::mutex> lock(mtx); // 在函数内部创建 lock_guard 对象,锁定互斥锁
for (int i = 0; i < n; ++i) {
std::cout << i << " ";
}
std::cout << std::endl;
} // lock_guard 对象在函数结束时自动析构,解锁互斥锁
int main() {
std::thread t1(print, 10);
std::thread t2(print, 10);
t1.join();
t2.join();
return 0;
}
```
在上面的代码中,我们定义了一个全局互斥锁 mtx,然后在 print 函数中创建了一个 std::lock_guard 对象 lock,它会在函数结束时自动析构,解锁互斥锁。这样,当多个线程同时调用 print 函数时,就不会出现竞争条件,保证了线程安全。