skip to content

Mutex and Lock Types

std::mutex is locked through RAII types: lock_guard, unique_lock, and scoped_lock that locks several at once without deadlock. Interviewers ask which lock type a design needs.

on this pageshow

explore

questions

6

In C++, why is a std::mutex locked through std::lock_guard rather than by calling lock() and unlock() directly?

level: juniorimportance: must knowfreq 78%

answer

  1. every exit path, not only the normal one
  2. constructor locks, destructor unlocks
  3. exceptions and early returns
  4. the scope is the critical section

basics

~20 s

std::lock_guard locks the mutex in its constructor and unlocks it in its destructor, so the mutex is released on every way out of the scope, including exceptions and early returns. A manual unlock() call is skipped by those paths and leaves the mutex locked.

solid answer

~40 s

`std::lock_guard<std::mutex>` is the RAII wrapper for one mutex: its constructor calls `m.lock()`, its destructor calls `m.unlock()`, and it can be neither copied nor moved. With manual calls, any `return`, `throw` or `break` between `lock()` and `unlock()` leaves the mutex owned. Another thread's next `lock()` then blocks forever, and a second `lock()` from the same thread breaks `std::mutex`'s precondition that the caller does not own it, which is undefined behaviour. With the guard, the critical section is exactly the guard's scope, so keep that scope small, if necessary with an extra pair of braces. Since C++17, class template argument deduction allows `std::lock_guard lock(m);`. The classic slip is an unnamed guard: `std::lock_guard<std::mutex>{m};` locks and unlocks within the same statement and protects nothing.

code

cpp · 30 lines
cpp
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <thread>

std::mutex stock_mu;
int on_hand = 5;
void pick_manual(int qty) {
    stock_mu.lock();
    if (qty > on_hand) throw std::runtime_error("short pick");  // skips unlock()
    on_hand -= qty;
    stock_mu.unlock();
}
void pick_guarded(int qty) {
    std::lock_guard<std::mutex> lock(stock_mu);   // destructor unlocks on every exit
    if (qty > on_hand) throw std::runtime_error("short pick");
    on_hand -= qty;
}
bool other_thread_can_lock() {
    bool got = false;
    std::thread([&] { if ((got = stock_mu.try_lock())) stock_mu.unlock(); }).join();
    return got;
}
int main() {
    try { pick_guarded(9); } catch (const std::exception&) {}
    std::cout << "after lock_guard: " << other_thread_can_lock() << '\n';
    try { pick_manual(9); } catch (const std::exception&) {}
    std::cout << "after manual:     " << other_thread_can_lock() << '\n';
    stock_mu.unlock();   // main still owns it
}

go deeper

for a junior

Recall that std::lock_guard locks in its constructor and unlocks in its destructor, so every exit path releases the mutex.

for a middle

Explain what happens to another thread and to the same thread when a manual unlock is skipped, and how to size the guard's scope.

for a senior

Review locking code for unnamed guards, references escaping the scope, slow work under the lock and half-applied updates on throw.

for a principal

Argue for a rule that bans bare lock() and unlock() calls and how a team enforces it in review or static analysis.

## The problem with lock() and unlock() A `std::mutex` has three operations: `lock()`, `try_lock()` and `unlock()`. Calling them by hand looks simple, but every path between the `lock()` and the `unlock()` must reach the `unlock()`. In a warehouse service, a pick function that locks the stock record and then throws on a short pick, returns early on a missing SKU, or calls a helper that throws `std::bad_alloc`, leaves the mutex **owned by a thread that has moved on**. What happens next depends on who touches it: - **Another thread** calling `lock()` blocks forever: the service hangs on the next pick of that item. - **The same thread** calling `lock()` again violates the precondition that the caller does not already own a `std::mutex`. A precondition violation in the standard library is undefined behaviour; the standard's note says the program can deadlock, and an implementation that detects it may report `resource_deadlock_would_occur`. - **Destroying** a mutex that is still owned, or letting a thread end while it owns one, is undefined behaviour as well. ## What std::lock_guard does `std::lock_guard<Mutex>` holds a reference to the mutex. The constructor calls `lock()` and the destructor calls `unlock()`. Because C++ runs destructors of automatic objects on **every** exit from a scope, normal fall-through, `return`, `break`, `continue` and exception unwinding alike, the mutex cannot stay locked by accident. It is the smallest useful lock type: | Feature | `std::lock_guard` | |---|---| | Locks in constructor | yes, or adopts an already-held lock with `std::adopt_lock` | | Unlocks early | no | | Copyable or movable | no | | Size and overhead | a reference to the mutex; nothing else to track | | Locks several mutexes | no; that is `std::scoped_lock` (C++17) | ## Choosing the scope The guard's lifetime *is* the critical section, so its placement is a design decision: 1. Compute everything that does not touch shared state **before** the guard. 2. Open a block, create the guard, read or update the shared data, close the block. 3. Do slow work, I/O, logging and calls into unknown code **after** the block. ```cpp int reserved; { std::lock_guard lock(stock_mu); // C++17 CTAD reserved = std::min(qty, on_hand); on_hand -= reserved; } notify_picker(reserved); // outside the lock ``` ## A mutex inside a class Most mutexes live next to the data they protect, as a member of the class that owns it. Three conventions keep that readable: - Declare the mutex **beside the members it guards**, with a comment naming them, so every reader knows which lock covers which field. - Declare it `mutable` when `const` member functions must lock it; locking is not a change to the object's observable state. - Take the guard at the **top of each public member function** that touches guarded data, and never hand out pointers or references to that data. A `std::mutex` is neither copyable nor movable, so a class with one loses its implicit copy and move operations. That is usually right: copying an object while another thread mutates it needs a deliberate lock on the source anyway. ## Mistakes that compile - **An unnamed guard.** `std::lock_guard<std::mutex>{m};` creates a temporary that is destroyed at the end of the statement, so the next lines run unlocked. libc++ marks the constructor `[[nodiscard]]` and clang warns; do not rely on it. With parentheses, `std::lock_guard<std::mutex>(m);` is parsed as a declaration of a new variable named `m` and fails to compile. - **A guard on the wrong mutex.** Each piece of shared data needs one agreed mutex; two functions guarding the same record with different mutexes provide no mutual exclusion. - **Returning a reference to guarded data.** The guard unlocks at the end of the function, and the caller then reads the data unprotected. - **A guard that outlives its mutex.** The standard makes it undefined behaviour if the mutex does not exist for the guard's whole lifetime. ## What the guard does not do `std::lock_guard` gives exception safety for **unlocking**, not for the data: if a throw happens halfway through an update of two fields, the mutex is released with the record half-updated. Order the operations so that anything that can throw happens before the first modification. And it does not make a design deadlock-free; locking several mutexes needs the tools on the next rung up.

  • What goes wrong with the statement std::lock_guard<std::mutex>{m}; in a function body?
    It creates an unnamed temporary guard that locks `m` and is destroyed at the end of that same statement, unlocking it again. Every following line runs without the lock. libc++ marks the constructor `[[nodiscard]]`, so clang warns, but the code compiles. Name the guard: `std::lock_guard<std::mutex> lock(m);`.
  • Does std::lock_guard make an update to two fields exception-safe?
    Only the unlocking. If the update throws after changing the first field, the guard still releases the mutex, and other threads see a half-updated record. Arrange the code so every operation that can throw runs before the first modification, or build the new value aside and swap it in.

  • Calling unlock() at the end of the function is just as safe as a lock_guard.
  • A thread may lock a std::mutex it already owns; the second lock() is ignored.
  • An unnamed std::lock_guard temporary keeps the mutex locked until the end of the block.
  • lock_guard makes a multi-field update exception-safe, not just the unlock.
  • A wider lock_guard scope is always safer, so lock the whole function.
open as a page

In C++, how do you lock the std::mutex of two inventory records for a stock transfer without risking deadlock?

level: middleimportance: must knowfreq 66%

basics

~10 s

Lock both with one call that avoids deadlock: std::scoped_lock lock(from.mu, to.mu) in C++17, or std::lock(from.mu, to.mu) followed by two lock_guards with std::adopt_lock in C++11. Guard against transferring a record to itself first.

open as a page

In C++, how does std::call_once with a std::once_flag initialize shared data exactly once, and what happens if the initializer throws?

level: middleimportance: should knowfreq 40%

basics

~20 s

std::call_once(flag, f) lets one caller at a time run f until a run returns normally; other callers wait, and every later call returns without running f but sees its results. If f throws, that caller gets the exception and a later call retries.

open as a page

For a read-mostly C++ stock catalog, how do std::shared_mutex and std::shared_lock work, and when do they fail to pay off?

level: middleimportance: should knowfreq 48%

basics

~20 s

std::shared_mutex (C++17) lets many threads hold shared ownership for reading while exclusive ownership excludes everyone. Readers lock through std::shared_lock, writers through std::unique_lock or lock_guard. It pays off when read sections are long and contended enough to outweigh its higher per-acquisition cost.

open as a page

In C++, when do you need std::unique_lock instead of std::lock_guard, and what does its extra flexibility cost?

level: middleimportance: should knowfreq 58%

basics

~20 s

Use std::unique_lock when the lock must do more than lock for a whole scope: defer or try locking, time out on a timed mutex, unlock early, or move ownership elsewhere. It costs an ownership flag checked in the destructor and more room for misuse.

open as a page

A C++ inventory class hangs when one locked member function calls another that locks the same std::mutex; why, and is std::recursive_mutex the fix?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Relocking a std::mutex the thread already owns breaks lock()'s precondition: undefined behaviour, usually a self-deadlock. std::recursive_mutex makes it legal, but the usual fix splits each operation into a locking public function and a private helper that assumes the lock.

open as a page