Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::scoped_lock — scope-bound lock ownership

std::scoped_lock owns mutex locks for its object's lifetime. Its constructor locks the supplied mutexes, and its destructor unlocks them. For multiple mutexes, it uses std::lock to avoid deadlock while acquiring them together.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <mutex>

{
    std::scoped_lock guard(m1, m2);
}

{
    std::lock(m1, m2);
    std::scoped_lock adopted(std::adopt_lock, m1, m2);
}

std::scoped_lock from <mutex> is an RAII guard: it ties lock ownership to the lifetime of a named object. Its destructor calls unlock() on each mutex, including when an exception exits the scope. The guard cannot be copied or moved; the mutexes must remain alive throughout its lifetime.

The ordinary constructor locks nothing for zero mutexes, calls lock() for one, and uses std::lock for multiple mutexes. A single mutex type must meet Cpp17BasicLockable; multiple mutex types must meet Cpp17Lockable. The algorithm avoids deadlock while acquiring those locks together, but does not prevent every deadlock in a program. If acquisition through std::lock throws, it releases locks acquired by that call before propagating the exception.

The std::adopt_lock overload does not lock the mutexes: it takes responsibility for unlocking them. The calling thread must already hold an exclusive lock on each one. Do not use the ordinary constructor to relock an already owned std::mutex. Name the guard: the temporary in std::scoped_lock{m1, m2}; is destroyed at the end of that statement.

The example updates two values while holding both locks and prints 7 23 after releasing them. It deliberately uses one thread for deterministic output; it does not demonstrate thread contention. In a concurrent program, all accesses to the same protected data must follow a consistent synchronization protocol.

Examples

#include <iostream>
#include <mutex>

int main() {
    std::mutex left_mutex;
    std::mutex right_mutex;
    int left = 10;
    int right = 20;

    {
        std::scoped_lock guard(left_mutex, right_mutex);
        left -= 3;
        right += 3;
    }

    std::cout << left << ' ' << right << '\n';
}

Result

7 23

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources