skip to content

A C++ function writes std::lock_guard<std::mutex>{counter_mutex}; before incrementing a shared counter, yet the counter still races; why?

level: seniorimportance: should knowfreq 42%

answer

  1. a guard with no name
  2. temporaries die at the semicolon
  3. parentheses can declare a variable
  4. name every guard

basics

~20 s

The guard has no name, so it is a temporary destroyed at the end of that statement: the mutex is locked and unlocked immediately, and the increment runs unprotected, which is a data race and undefined behaviour.

solid answer

~40 s

An unnamed object such as `std::lock_guard<std::mutex>{counter_mutex};` is a temporary, and a temporary is destroyed at the end of the full-expression that created it, so `~lock_guard()` unlocks at the semicolon and `++applied` runs with no lock held. The race is undefined behaviour, so the wrong count is a symptom, not a guaranteed output. The parenthesised spelling is worse: `std::lock_guard<std::mutex>(counter_mutex);` declares a variable named `counter_mutex`, which fails to compile for `lock_guard` (it has no default constructor) but compiles silently for `std::unique_lock`, leaving an empty lock that owns nothing. Fix it by naming the guard: `std::lock_guard guard(counter_mutex);` (C++17 deduction) or `std::scoped_lock`. Both libc++ and libstdc++ mark the constructors `[[nodiscard]]`, an implementation choice, so a warning flags the temporary.

code

cpp · 20 lines
cpp
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

std::mutex counter_mutex;
long applied = 0;

void record_applied() {
    std::lock_guard<std::mutex>{counter_mutex};   // BUG: temporary, unlocked at the ';'
    ++applied;                                    // runs with no lock held
}

int main() {
    std::vector<std::thread> workers;
    for (int i = 0; i < 4; ++i)
        workers.emplace_back([] { for (int n = 0; n < 100000; ++n) record_applied(); });
    for (auto& t : workers) t.join();
    std::cout << applied << '\n';
}

go deeper

for a junior

Recall that a guard protects only while it exists, and an object without a name disappears at the end of its statement.

for a middle

Explain full-expression lifetime for temporaries and why the parenthesised form is a declaration, failing for lock_guard and compiling for unique_lock.

for a senior

Diagnose from the symptom: a racing counter despite a lock line means checking the guard's lifetime, confirming with ThreadSanitizer, and treating the bad count as undefined behaviour.

for a principal

Turn the lesson into enforcement: warnings as errors for nodiscard and vexing-parse diagnostics, sanitizer runs in CI, and a review rule that every guard is named.

## The bug ```cpp void record_applied() { std::lock_guard<std::mutex>{counter_mutex}; // looks like a lock ++applied; // is not protected } ``` The line reads like "lock the mutex for this function". It is not. The guard has **no name**, so it is a **temporary object**, and the language destroys a temporary at the end of the **full-expression** in which it was created: here, at the semicolon. Its constructor locks `counter_mutex`, its destructor unlocks it, and both happen before `++applied` executes. Four threads incrementing the counter then race. ## Why the symptom is not an output Two threads writing the same `long` without synchronisation is a **data race**, which the standard makes undefined behaviour. The program may print a total below the expected 400000, may print the right total on a quiet machine, or may misbehave in ways no print shows. ThreadSanitizer (`-fsanitize=thread`) reports it as `WARNING: ThreadSanitizer: data race` with both writes pointing at the increment line. The diagnosis is the missing lifetime, not the number. ## The parenthesised spelling is a declaration The other common slip removes the braces: - `std::lock_guard<std::mutex>(counter_mutex);` is parsed as a **declaration** of a variable named `counter_mutex` of type `std::lock_guard<std::mutex>`, with redundant parentheses around the name. `lock_guard` has no default constructor, so this fails to compile. - `std::unique_lock<std::mutex>(counter_mutex);` is the same declaration, but `std::unique_lock` **has** a default constructor. It compiles, declares an empty `unique_lock` that owns no mutex, and the new name shadows the real mutex for the rest of the block. clang reports `-Wvexing-parse`: "parentheses were disambiguated as redundant parentheses around declaration of variable named 'counter_mutex'". ## The fix: give the guard a name | Spelling | What it creates | Lock held until | |---|---|---| | `std::lock_guard<std::mutex>{m};` | a temporary | the end of the statement | | `std::lock_guard<std::mutex>(m);` | a declaration of a new `m` (ill-formed) | it does not compile | | `std::lock_guard<std::mutex> g(m);` | a named local | the end of the block | | `std::lock_guard g(m);` (C++17) | a named local, type deduced | the end of the block | A named guard is an automatic object whose lifetime is the enclosing block, which is exactly the critical section. Keep the block as small as the data it protects: open a nested `{ }` scope if only two lines need the lock. ## How tools catch it - **`[[nodiscard]]` on the constructors.** The standard's synopsis of `lock_guard` does not require it, but both libc++ and libstdc++ (in its GCC 16.2 headers) mark `lock_guard`'s constructors `[[nodiscard]]`. With libc++, clang warns: "ignoring temporary created by a constructor declared with 'nodiscard' attribute". - **`-Wvexing-parse`** in clang flags the parenthesised declaration. - **ThreadSanitizer** catches the race at run time, whichever spelling caused it. - **Code review**: a guard without a name is always a bug, so it is a cheap rule to check. Which lock type to pick (`lock_guard`, `unique_lock`, `scoped_lock`) and how they differ is a separate question; the point here is that any of them protects only for as long as the object lives. ## Diagnosing it from a bug report A report says "the counter is sometimes low even though it is locked". A reliable path to the cause: 1. Read the lock line and ask when the guard object is destroyed: unnamed, static, or heap-allocated guards are the usual suspects. 2. Rebuild with `-Wall` and read the warnings: the nodiscard and vexing-parse warnings point at the exact line. 3. Run the workload under `-fsanitize=thread` to confirm the race and get both stack traces. 4. Fix by naming the guard, then rerun the sanitizer rather than trusting a correct-looking count. ## The general lesson RAII ties a resource to an object's **lifetime**, so the resource is held exactly as long as the object exists. Every RAII bug is a lifetime bug: a temporary that dies too early, a static that lives too long, a heap object nobody destroys. When a guard "does not work", ask first when its object is destroyed.

  • Why does std::unique_lock<std::mutex>(counter_mutex); compile when the lock_guard version does not?
    Both lines declare a new variable named `counter_mutex`, because redundant parentheses around a declarator are allowed. `std::lock_guard` has no default constructor, so its declaration is ill-formed; `std::unique_lock` has one, so it compiles into an empty lock owning no mutex that shadows the real one. clang warns with `-Wvexing-parse`.
  • What happens if the guard is declared static std::lock_guard<std::mutex> guard(counter_mutex); inside the function?
    A static local is constructed once, on the first call, and destroyed only at program exit. The first call locks the mutex and nothing unlocks it until exit; later calls skip the declaration entirely, so they increment the counter with no lock, while any other code that locks the same mutex blocks forever. A guard must be an automatic local.

  • An unnamed lock_guard holds the mutex until the end of the block
  • The wrong count is the program's defined output for this race
  • std::lock_guard<std::mutex>(m); locks m like a named guard does
  • The standard requires lock_guard's constructor to be [[nodiscard]]
  • Making the guard static keeps it locked only for this call