Interview Q&A · C++ · 14 questions in this topic
Threads, Mutexes & Atomics — C++ Interview Q&A
Writing correct concurrent C++ — threads, data races, mutexes, condition variables, atomics and futures. Part of Concurrency · 213 questions in the C++ bank.
How do you create and manage a `std::thread`?
Answer
Construct std::thread with a callable plus arguments; the new thread starts immediately. Every joinable thread must be joined (wait) or detached (release) before its destructor — destroying a joinable thread terminates. Prefer joining, wrap in RAII guards, and pass arguments by reference only with std::ref.
C++20 std::jthread improves this: it joins automatically and supports stop tokens.
Example
#include <thread> void work(int n) {} std::thread t(work, 42); // ... t.join(); // must join or detach before t dies
What is a data race and why is it undefined behavior?
Answer
A data race is two unsynchronized accesses to the same memory with at least one write (and neither is atomic). In C++ it is undefined behavior — not merely a wrong value — so the compiler may assume races never happen and optimize accordingly, making symptoms unreproducible.
Fix with mutexes for compound operations or atomics for single locations; ThreadSanitizer finds races empirically.
Example
int counter = 0; // two threads: counter++ — data race (read-modify-write)! std::atomic<int> safe{0}; // two threads: safe.fetch_add(1) — defined
💡 Say undefined behavior, not just wrong answer — the UB framing is what interviewers check.
What is a mutex and how do `lock_guard`, `unique_lock` and `scoped_lock` differ?
Answer
A mutex serializes access to shared data: lock before touching, unlock after. lock_guard is the simple scoped locker (no manual unlock, no flexibility). unique_lock adds unlock/relock, try-lock and condition-variable compatibility at slight cost. scoped_lock (C++17) locks multiple mutexes deadlock-free in one call.
Default to lock_guard; unique_lock only when you need its flexibility; scoped_lock for multi-mutex acquisition.
Example
#include <mutex> std::mutex m; void add() { std::lock_guard<std::mutex> g(m); // auto-unlock, exception safe // touch shared data } void transfer(std::mutex& a, std::mutex& b) { std::scoped_lock both(a, b); // deadlock-free multi-lock }
💡 Never call lock/unlock manually — the guard choice is the whole modern answer.
What is a deadlock and what are the four Coffman conditions?
Answer
Deadlock is threads waiting on each other forever. Coffman conditions: mutual exclusion, hold-and-wait, no preemption, circular wait. Break any one: lock ordering (breaks circular wait), try-lock with backoff, lock-free atomics, or scoped multi-lock acquisition.
Consistent global lock ordering is the most practical prevention in real codebases.
Key points
- 1Mutual exclusion — resource cannot be shared.
- 2Hold-and-wait — thread holds one lock while wanting another.
- 3No preemption — locks cannot be forcibly taken.
- 4Circular wait — a cycle of waiting threads.
Example
// prevention: one global order, always acquired the same way // std::scoped_lock(a, b); // internally ordered, deadlock-free
What is a condition variable and why does wait need a predicate loop?
Answer
A condition_variable lets threads sleep until shared state changes: waiters atomically release the mutex and sleep; notifiers wake them. Spurious wakeups plus stolen notifications mean wait must re-check its condition in a loop — the predicate form (cv.wait(lock, pred)) does exactly that.
Always mutate the shared state under the same mutex before notifying, and prefer notify_all when multiple waiters may proceed.
Example
std::mutex m; std::condition_variable cv; bool ready = false; // waiter: { std::unique_lock<std::mutex> lk(m); cv.wait(lk, []{ return ready; }); // predicate loop, spurious-safe } // notifier: { std::lock_guard<std::mutex> lk(m); ready = true; } cv.notify_all();
What is `std::atomic` and what does it guarantee?
Answer
std::atomic makes single-location operations indivisible: loads, stores, read-modify-write (fetch_add, exchange, compare_exchange) execute without torn reads or lost updates. It does not compose — two atomics updated together still race as a pair without a mutex.
Default sequential consistency is easiest to reason about; relaxed/acquire-release orderings are expert optimizations with weaker guarantees.
Example
#include <atomic> std::atomic<int> hits{0}; hits.fetch_add(1, std::memory_order_relaxed); // atomic increment
💡 Atomicity is per-location, not per-transaction — that boundary is the key insight.
What are memory orders (relaxed, acquire, release, seq_cst)?
Answer
Memory orders constrain how atomic operations synchronize with other memory: relaxed guarantees atomicity only; release publishes prior writes to an acquire-loader of the same atomic; acquire observes them; seq_cst (default) adds a global total order. Correct lock-free code pairs release-stores with acquire-loads.
Rule: default to seq_cst, weaken to acquire/release only with a proven protocol (and tests under ThreadSanitizer plus model checkers).
Key points
- 1relaxed — atomicity, no ordering.
- 2release/acquire — publish/subscribe pairing.
- 3seq_cst — global order, default, slowest but safest.
💡 Publish-subscribe is the mental model for release/acquire pairing.
What is the difference between mutex-based and lock-free synchronization?
Answer
Mutexes serialize whole critical sections: simple, composable, but blocking (contention, priority inversion, deadlock risk). Lock-free atomics make progress without locks: no blocking or deadlock, but only for carefully designed single-location protocols, with ABA hazards and hard correctness proofs.
Guideline: mutexes by default; lock-free for measured hot paths (queues, counters) using reviewed primitives, never hand-rolled CAS loops on first attempt.
Example
// simple counter: mutex version is obviously correct // lock-free version needs fetch_add + ordering proof
What are `std::future`, `std::promise` and `std::async`?
Answer
promise/future is a one-shot channel: the producer sets a value/exception on the promise, the consumer get()s it from the future (blocking once). async launches a callable, returning a future — with launch::async on a new thread or deferred for lazy evaluation.
Prefer async/futures or threads+jthread for structured tasks; raw condition-variable plumbing only for custom schedulers and queues.
Example
#include <future> auto fut = std::async(std::launch::async, []{ return 42; }); int v = fut.get(); // blocks once, rethrows stored exceptions
💡 One-shot channel plus exception transport is the future value proposition in one line.
What is the difference between `std::mutex`, `recursive_mutex` and `shared_mutex`?
Answer
mutex is non-recursive (relocking deadlocks) — the default. recursive_mutex allows the same thread to relock (for re-entrant code) at bookkeeping cost. shared_mutex (C++17) allows multiple readers or one writer: shared_lock for readers, unique_lock for writers.
Avoid recursive_mutex by restructuring (it hides locking bugs); use shared_mutex only when reads vastly outnumber writes and critical sections are short.
Example
#include <shared_mutex> std::shared_mutex rw; // reader: std::shared_lock<std::shared_mutex> r(rw); // writer: std::unique_lock<std::shared_mutex> w(rw);
What is false sharing and how do you fix it?
Answer
False sharing is threads hammering different variables that share one cache line: every write invalidates the line for all cores, so performance collapses despite no logical sharing. Fix by padding/aligning hot per-thread data to cache-line boundaries (hardware_destructive_interference_size, C++17) or giving each thread local accumulation merged at the end.
Symptom: scaling stalls at 2 threads on an embarrassingly parallel loop — profilers show cache-coherence traffic, not lock contention.
Example
#include <new> // hardware_destructive_interference_size (C++17) struct alignas(std::hardware_destructive_interference_size) Slot { long value = 0; }; // each thread gets its own cache line
What is `thread_local` storage?
Answer
thread_local gives each thread its own instance with thread lifetime: constructed on first use in that thread, destroyed at thread exit. Ideal for per-thread caches, RNGs and scratch buffers without synchronization.
Costs: total memory scales with thread count, construction/destruction ordering across threads needs care, and thread_local in DLLs/shared libraries has platform quirks.
Example
thread_local unsigned seed = 12345; // each thread: own seed thread_local std::vector<char> scratch; // per-thread buffer, no locks
How do you stop a thread safely? (Cooperative cancellation.)
Answer
Threads cannot be killed safely — stopping is cooperative: the worker polls a stop flag (atomic<bool> or C++20 stop_token) at safe points and unwinds normally, releasing RAII resources. jthread wires stop_token in automatically; with thread, pass an atomic flag or condition-variable generation counter.
Never terminate/detach-and-forget workers holding locks or owning resources — join everything at shutdown.
Example
#include <stop_token> void worker(std::stop_token st) { while (!st.stop_requested()) { /* chunk of work */ } } std::jthread t(worker); t.request_stop(); // cooperative, safe unwind
💡 Cannot-kill plus poll-a-flag is the complete stopping philosophy.
What tools detect threading bugs?
Answer
ThreadSanitizer (-fsanitize=thread) finds data races and lock-order issues at runtime; Helgrind/DRD do similar under valgrind with higher overhead. Static analyzers and clang thread-safety annotations (GUARDED_BY, REQUIRES) catch locking discipline at compile time. Stress tests plus deterministic schedulers (or model checkers for lock-free code) cover interleavings that single runs miss.
Workflow: annotate, run TSan in CI on stress workloads, fix races — never ship a known race.
Example
// build with ThreadSanitizer: // g++ -fsanitize=thread -g -O1 app.cpp -pthread
💡 TSan in CI on stressed workloads is the single highest-value threading practice.
Recommended resourcesAffiliate links · may earn us a commission