KatInterview

Mutex Mechanics and Safe Shared State Access in C++

System DesignModel answer
MediumModel answerSystem Designconcurrencycppthreading

Last updated

Explain how a C++ mutex enforces exclusive access, how locking works under contention, and how to correctly guard a multi-threaded shared counter.

In a multi-threaded C++ program, multiple threads need to increment a shared integer counter. The counter is a plain (non-atomic) int, and you decide to protect it with std::mutex.

Walk through how the mutex provides correct synchronization:

  1. Explain what guarantee the C++ standard gives you when one thread unlocks a mutex and another thread subsequently locks it. Why does this guarantee matter for a non-atomic counter?
  2. Describe a plausible implementation strategy for the fast (uncontended) path versus the slow (contended) path. What primitives might the runtime or operating system use? Make clear which parts are standard-mandated and which are implementation choices.
  3. Provide a short C++ example where several worker threads safely increment a shared counter using RAII locking.
  4. Discuss what happens if even one code path modifies or reads the counter without acquiring the mutex. Is partial compliance with the locking discipline sufficient?
  5. Cover common pitfalls: deadlocks (including lock ordering across multiple mutexes), non-recursive locking of the same mutex, and the absence of a portable fairness guarantee.

Assume the mutex and the counter both outlive all worker threads. Use only std::mutex and standard C++ threading facilities. Distinguish standard guarantees from platform-specific implementation details throughout your answer.

Hints

Hint 1

The standard guarantees a happens-before relationship: an unlock on one thread synchronizes-with a successful lock on another thread, making prior writes visible to the acquiring thread.

Hint 2

An uncontended lock can often be acquired with a single atomic compare-and-swap; contention typically falls back to an OS-level futex or condition variable to avoid busy-spinning.

Hint 3

Every conflicting access to the shared state must go through the mutex. A single unsynchronized read or write can produce a data race, making the entire program's behavior undefined.