std::scoped_lock
in C++std::scoped_lock
is a synchronization primitive introduced in C++17 that simplifies the process of acquiring multiple locks simultaneously, helping to avoid deadlocks and ensuring exception safety. It provides a convenient way to lock one or more mutexes at the same time, and it automatically releases those locks when the std::scoped_lock object goes out of scope.
std::scoped_lock
is designed to acquire multiple locks in a deadlock-free manner, which is crucial when locking multiple mutexes simultaneously.std::scoped_lock
follows the RAII (Resource Acquisition Is Initialization) principle, ensuring that mutexes are automatically released when the std::scoped_lock
object is destroyed.Here’s an example where std::scoped_lock
is used to safely lock two mutexes simultaneously:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mutex1;
std::mutex mutex2;
void threadFunction1() {
for (int i = 0; i < 5; ++i) {
std::scoped_lock lock(mutex1, mutex2); // Lock both mutexes safely
std::cout << "Thread 1 is executing with locks on both mutex1 and mutex2" << std::endl;
// Critical section protected by both mutexes
}
}
void threadFunction2() {
for (int i = 0; i < 5; ++i) {
std::scoped_lock lock(mutex1, mutex2); // Lock both mutexes safely
std::cout << "Thread 2 is executing with locks on both mutex1 and mutex2" << std::endl;
// Critical section protected by both mutexes
}
}
int main() {
std::thread t1(threadFunction1);
std::thread t2(threadFunction2);
t1.join();
t2.join();
return 0;
}
std::scoped_lock lock(mutex1, mutex2);
: In both threadFunction1
and threadFunction2
, we use std::scoped_lock
to acquire locks on mutex1
and mutex2
simultaneously. This ensures that both mutexes are locked in a deadlock-free manner.std::scoped_lock
object lock goes out of scope (at the end of the loop iteration in this case), ensuring exception safety and proper resource management.The output will interleave messages from both threads, showing that they are both acquiring and releasing locks on the two mutexes safely:
Thread 1 is executing with locks on both mutex1 and mutex2
Thread 2 is executing with locks on both mutex1 and mutex2
Thread 1 is executing with locks on both mutex1 and mutex2
Thread 2 is executing with locks on both mutex1 and mutex2
std::scoped_lock
?std::scoped_lock
helps prevent deadlocks by locking the mutexes in a consistent order.std::scoped_lock
is a valuable tool in C++17 that simplifies and secures the process of locking multiple mutexes. It helps prevent deadlocks and ensures that resources are managed properly by automatically unlocking mutexes when the scope ends. This makes it an essential component in modern C++ multithreading, especially in scenarios where multiple resources need to be accessed concurrently.