Mutex Mechanics and Safe Shared State Access in C++
System DesignModel answerLast 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:
- 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?
- 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.
- Provide a short C++ example where several worker threads safely increment a shared counter using RAII locking.
- 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?
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Standard-level guarantee
The C++ memory model defines a synchronizes-with relationship: when thread A unlocks a mutex and thread B later successfully locks that same mutex, every memory write that A performed before the unlock is visible to B after the lock. This is a happens-before edge enforced by the standard, independent of the underlying platform.
For a non-atomic counter this is essential. Without synchronization, concurrent reads and writes to the same int are a data race, which is undefined behavior in C++. The mutex does not just prevent interleaved execution of the critical section; it also establishes the memory visibility needed so that each thread sees a consistent value of the counter after acquiring the lock.
2. Uncontended vs. contended lock implementation
The standard mandates mutual exclusion and the synchronizes-with semantics, but leaves the implementation to the runtime and OS.
- Fast path (uncontended): The lock attempt can use a single atomic operation such as compare-and-swap (CAS) on a flag word inside the mutex object. If the current value is "unlocked," it is atomically changed to "locked" and the thread enters the critical section. This involves no system call and typically costs tens of nanoseconds.
- Slow path (contended): If the CAS fails because another thread holds the lock, the thread must wait. Spinning briefly can help if the critical section is short, but prolonged spinning wastes CPU cycles. Most implementations fall back to an OS-level blocking primitive such as a futex (Linux) or a kernel-level event (Windows). The waiting thread is descheduled so the OS can run other work, and it is woken when the mutex is released. Whether the implementation spins before blocking, and for how long, is an implementation choice the standard does not specify.
Fairness, such as waking waiters in FIFO order, is also not guaranteed by the standard. An implementation may allow a newly arriving thread to "steal" the lock ahead of already-waiting threads.
3. Safe increment example
#include <mutex>
#include <thread>
#include <vector>
class SharedCounter {
public:
void increment() {
std::lock_guard<std::mutex> lock(mtx_);
++value_;
}
int get() const {
std::lock_guard<std::mutex> lock(mtx_);
return value_;
}
private:
mutable std::mutex mtx_;
int value_ = 0;
};
void worker(SharedCounter& counter, int iterations) {
for (int i = 0; i < iterations; ++i) {
counter.increment();
}
}
int main() {
SharedCounter counter;
std::vector<std::thread> threads;
const int num_threads = 8;
const int increments_per_thread = 10000;
for (int i = 0; i < num_threads; ++i) {
threads.emplace_back(worker, std::ref(counter), increments_per_thread);
}
for (auto& t : threads) {
t.join();
}
// counter.get() == num_threads * increments_per_thread
return 0;
}
std::lock_guard provides RAII-based locking: the mutex is acquired on construction and released on destruction, even if an exception propagates out of the critical section. std::unique_lock is an alternative that supports deferred locking, manual unlock, and use with condition variables. std::scoped_lock (C++17) extends the same idea to multiple mutexes simultaneously.
4. Why partial compliance fails
Every conflicting access to the shared state must acquire the mutex. If even one thread reads or writes the counter without locking, two problems arise:
- Data race: The unsynchronized access and a synchronized access can run concurrently, producing undefined behavior. The C++ model does not guarantee anything once a race exists.
- Broken visibility: The unsynchronized reader may observe a stale or partially written value because it lacks the happens-before edge that locking would provide.
A common mistake is locking only on writes but not on reads, reasoning that "reads are safe." For a non-atomic variable this is incorrect: a concurrent write while the read happens is still a data race.
5. Common pitfalls
- Deadlock: When a thread acquires mutex A and then waits for mutex B, while another thread holds B and waits for A, both block forever. The fix is a consistent lock-ordering discipline, or using
std::scoped_lock(A, B)which acquires multiple mutexes with deadlock-avoidance logic. - Non-recursive locking:
std::mutexcannot be locked again by the same thread that already holds it. Doing so is undefined behavior (typically a deadlock). If re-entrant locking is genuinely needed,std::recursive_mutexexists, but it is usually better to refactor the code to avoid recursive locking. - No fairness guarantee: The standard does not promise that the longest-waiting thread acquires the lock next. Starvation is theoretically possible, though rare in practice. If bounded wait time is required, higher-level synchronization primitives or a custom queuing mechanism may be needed.
- Forgetting RAII: Manually calling
lock()andunlock()is fragile. An early return or exception skips the unlock, leaving the mutex permanently locked. Always preferlock_guardorunique_lock.