Millennium · Behavioral
How a C++ Mutex Protects Shared State
TrueInterview
September 26, 2026 · 1 min read
How does a C++ mutex function, and what does an application need to do for it to properly guard shared state?
Describe the language-level guarantee, one possible uncontended versus contended lock implementation, and a brief C++ example that safely increments shared state. Also discuss what fails when only some accesses follow the locking discipline.
Constraints & Assumptions
- Use
std::mutexand standard C++ threads. - The shared state is a non-atomic counter touched by multiple threads.
- Assume the mutex and counter stay alive until all worker threads complete.
- Separate standard guarantees from implementation choices; do not presume a particular operating-system primitive, fairness policy, or spin duration.
Clarifying Questions to Ask
- Does the protected state need to maintain an invariant across several fields, or is it just a single counter?
- May code inside the critical section throw or return before completing?
- Can this operation acquire another mutex, or call back into a function that takes the same mutex?
Hint — Ownership and visibility are separate concerns: Explain why two threads cannot hold the same mutex at the same time, and why a later owner can see writes made by an earlier owner.
What a Strong Answer Covers
- Mutual exclusion and the synchronization relation between an unlock and the next successful lock on that same mutex.
- A shared locking convention applied to every conflicting access of the non-atomic state.
- RAII through
std::lock_guardorstd::unique_lock, along with exception safety. - The distinction between a potential atomic fast path and operating-system-assisted blocking under contention.
- Deadlock, non-recursive ownership, and the lack of a portable fairness guarantee.
Follow-up Questions
- How would you safely acquire two mutexes required by a single operation?
- When is
std::unique_lockmore suitable thanstd::lock_guard?
Overview: Explain C++ mutex ownership, memory visibility, RAII locking, contention, and deadlock prevention using a shared-counter example.
Loading comments…