liveBook · Manning

Std::scoped_lock

As explained in C++ Concurrency in Action, Second Edition

A C++ standard library class template that acquires ownership of one or more lockable objects and releases them on destruction.

`std::scoped_lock` is a variadic RAII template for acquiring one or more lockable objects. For multiple mutexes, its constructor uses the same algorithm as `std::lock`; when construction completes, all supplied mutexes are locked, and the destructor unlocks them. section 3.2.4

void swap(X& lhs, X& rhs)
    {
        if(&lhs==&rhs)
            return;
        std::scoped_lock guard(lhs.m,rhs.m);       #1
        swap(lhs.some_detail,rhs.some_detail);
    }


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":4,\"ch\":51},{\"line\":4,\"ch\":53}]]"}
!@%STYLE%@!

In this swap operation, one guard acquires both object mutexes before the protected data is swapped; its destruction releases them. section 3.2.4

C++17 class template argument deduction can infer the mutex types from the constructor arguments. Acquiring several locks together can help avoid deadlock, but `std::scoped_lock` does not prevent deadlock when locks are acquired separately. section 3.2.4

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Explains variadic construction, locking behavior, destruction-time release, and C++17 deduction; does not prevent deadlock from separately acquired locks.
Examples
Rewrites a two-object swap to lock both mutexes with one scoped_lock guard.
What you can do after
Apply it to acquire multiple mutexes together and release them automatically around a protected operation.
How it connects
Connects std::lock, std::lock_guard, mutexes, RAII, and deadlock avoidance.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.