std::scoped_lock


Keyword: 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.

Key Features

Example: Using std::scoped_lock to Safely Lock Multiple Mutexes

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;
}

Explanation

Expected Output

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

Why Use std::scoped_lock?

When to Use std::scoped_lock

Conclusion

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.

Previous Page | Course Schedule | Course Content