std::scoped_lock
时间: 2023-10-24 11:09:00 浏览: 100
std::scoped_lock is a C++11 feature that provides a way to lock multiple mutexes at the same time. It is a type of RAII (Resource Acquisition Is Initialization) lock that locks the provided mutexes in their given order when the scoped_lock object is created and unlocks them in the reverse order when the object is destroyed.
The syntax for creating a scoped_lock object is as follows:
```
std::mutex mutex1;
std::mutex mutex2;
void function() {
std::scoped_lock lock(mutex1, mutex2); // lock mutex1 and mutex2
// critical section
} // unlock mutex2 and mutex1
```
In the above example, the scoped_lock object `lock` is created with `mutex1` and `mutex2` as its arguments. When `lock` is created, it locks `mutex1` and `mutex2` in that order. When `lock` is destroyed at the end of the function, it unlocks `mutex2` and `mutex1` in the reverse order. This ensures that the mutexes are always locked and unlocked in the correct order, preventing deadlocks and other synchronization issues.
阅读全文