Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::lock_guard — scope-bound lock ownership

std::lock_guard from <mutex> manages a lock using RAII. The constructor that takes only the mutex locks it. The std::adopt_lock overload takes responsibility for an exclusive lock the current thread already holds, without calling lock(). In both cases, the destructor unlocks the mutex. A named object protects a critical section throughout its lifetime.

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

Syntax

#include <mutex>
std::lock_guard<Mutex> guard(m);
std::lock_guard<Mutex> guard(m, std::adopt_lock);

std::lock_guard<Mutex> ties lock ownership to object lifetime (RAII). The constructor taking m calls m.lock(), and the destructor calls m.unlock(). Leaving the scope, including through return or exception stack unwinding, releases a successfully acquired lock.

The Mutex type must satisfy Cpp17BasicLockable. The mutex must exist throughout the guard's lifetime; violating this requirement causes undefined behavior. The guard cannot be copied or moved and provides no operation for unlocking early.

The overload taking std::adopt_lock assumes responsibility for an already-owned lock without calling lock(). It requires the current thread to already hold an exclusive lock on that mutex. Give the guard a name: a temporary is destroyed at the end of the full expression instead of protecting subsequent statements.

In the example, both threads protect every increment of counter with the same mutex. The read occurs only after both join() calls, so the expected result is 2000 regardless of thread scheduling.

Examples

#include <iostream>
#include <mutex>
#include <thread>

int main() {
    std::mutex m;
    int counter = 0;

    auto increment = [&] {
        for (int i = 0; i < 1000; ++i) {
            std::lock_guard<std::mutex> guard(m);
            ++counter;
        }
    };

    std::thread first(increment);
    std::thread second(increment);
    first.join();
    second.join();

    std::cout << counter << '\n';
}

Result

2000

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