Concurrency, Shared State, And Race Conditions
Asked of: Software Engineer
Last updated

What's being tested
This topic tests whether you can reason precisely about shared mutable state, identify when operations interleave incorrectly, and choose synchronization proportional to the required correctness and performance. The interviewer is probing more than whether you know mutex syntax: you should be able to explain the happens-before relationship, distinguish atomicity from visibility and ordering, and construct an execution that demonstrates a bug. Jane Street cares because concurrent trading and market-data systems must remain correct under high contention while avoiding unnecessary latency, blocking, and nondeterminism.
Core knowledge
-
A data race occurs when two threads access the same memory concurrently, at least one access is a write, and there is no synchronization establishing a valid ordering. A race is a correctness bug even if tests rarely reproduce it.
-
Atomicity, visibility, and ordering are separate guarantees. An atomic increment prevents torn updates, visibility makes another thread observe a write, and ordering constrains reordering; a
volatile-style mechanism may provide visibility without makingx++atomic. -
Use a
mutexwhen a critical section protects an invariant involving multiple fields. The invariant must be restored before unlocking; locking each individual field access can still expose an inconsistent combination of values. -
A compare-and-swap (CAS) loop implements optimistic synchronization: read the old value, compute a candidate, and retry if another thread changed it. It works well for short, low-contention updates but can waste CPU under contention and must handle the ABA problem.
-
Linearizability means each operation appears to take effect at one instant between invocation and response. Identify that linearization point—for example, a successful CAS or a lock-protected map mutation—to prove concurrent behavior matches a legal sequential history.
-
A happens-before edge can arise from
mutexunlock/lock, thread start/join, message passing, or a language-level atomic operation. Without such an edge, observing a write is not guaranteed, even when the hardware “usually works.” -
Deadlock requires mutual exclusion, hold-and-wait, no preemption, and circular wait. Prevent it with a global lock-ordering rule, smaller critical sections,
try_lockwith rollback, or ownership designs that avoid nested locks. -
Condition variables coordinate state transitions, not events. Always wait in a loop—
while (!predicate) wait(cv, lock)—because wakeups can be spurious and another thread may consume the condition before the waiter reacquires the lock. -
Lock-free means system-wide progress: some operation completes in a bounded number of steps, not that every thread completes. Wait-free guarantees per-thread progress and is stronger; both introduce memory-reclamation complexity for removed nodes.
-
False sharing occurs when independent variables occupy the same cache line and different cores repeatedly write them. Padding or per-thread counters can reduce cache-coherence traffic, but measure before adding memory overhead or complicating aggregation.
-
Prefer message passing, immutable snapshots, or ownership transfer when possible. A single-owner event loop can eliminate many races, while a read-copy-update or copy-on-write design can make reads cheap at the cost of allocation and update latency.
-
Testing must include adversarial schedules, not just repeated normal runs. Use thread sanitizers, deterministic schedulers, stress tests with barriers, and model-based checks; a test that “passed 10,000 times” does not establish correctness.
Worked example
Representative problem: Design a thread-safe shared counter. In the first 30 seconds, clarify whether increments and reads must be linearizable, whether the counter can overflow, the expected read/write ratio, and whether approximate results are acceptable. I would organize the answer around the correctness contract, synchronization strategy, contention profile, and testing plan. For exact semantics, a mutex around the counter is the simplest proof: the increment’s linearization point is its update while holding the lock. If contention is low and the operation is only a single integer update, an atomic fetch-add may reduce blocking, but I would explicitly discuss memory ordering and whether the API needs a consistent snapshot alongside other fields. For high-frequency per-thread updates where temporary approximation is acceptable, thread-local counters periodically aggregated by a reader may outperform one globally contended cache line. I would call out overflow and shutdown behavior rather than silently relying on language-specific wraparound. I would close by saying that, with more time, I would benchmark mutex, atomic, and sharded implementations under realistic contention and run a race detector plus linearizability-oriented tests.
A second angle
The same reasoning applies to a shared in-memory order book, but the invariant is more complex than a counter: quantities, prices, and indexes must agree. A lock per price level may improve parallelism, yet operations crossing multiple levels require a lock-order rule or a higher-level serialization mechanism. If readers need a coherent view while writers update frequently, immutable snapshots or a single-writer design may be safer than independently locking every structure. The key question becomes not “which primitive is fastest?” but “what consistency boundary must one observation satisfy?”
Common pitfalls
Pitfall: Saying “the increment is one instruction, so it is safe” confuses instruction-level behavior with a read-modify-write race. Two threads can both read the same value and each publish the same successor, losing an update.
A candidate may recommend volatile or an atomic variable without stating the required semantics. A stronger answer explains whether the operation needs atomic read-modify-write, release/acquire publication, sequential consistency, or merely eventual aggregation.
Pitfall: Treating “use a lock” as a complete design misses deadlock, lock scope, starvation, and contention. Name the protected invariant, lock ownership, lock ordering, and what work must remain outside the critical section.
Over-focusing on lock-free algorithms is another depth mistake. CAS, hazard pointers, epochs, and ABA mitigation are valuable only when measurement shows a mutex or ownership-based design is inadequate; correctness and a clear proof come first.
Connections
An interviewer may pivot to distributed consistency, where process-local mutexes no longer protect shared state, or to transactional memory and database isolation levels. Be ready for memory reclamation, backpressure, actor/message-passing architectures, and performance topics such as cache coherence and tail latency.
Further reading
-
The Art of Multiprocessor Programming — rigorous treatment of linearizability, lock-free algorithms, and concurrent objects.
-
C++ Concurrency in Action — practical explanation of memory ordering, atomics,
mutexes, and condition variables. -
Java Memory Model and Thread Specification — a precise reference for visibility, synchronization, and happens-before reasoning.
Related concepts
- Synchronization Primitives And Deadlock
- Concurrency, Deadlocks, And SynchronizationSoftware Engineering Fundamentals
- Concurrency Control And Thread SafetySystem Design
- Concurrency, OS Threads, And MemorySoftware Engineering Fundamentals
- Concurrency, Scheduling, and State MachinesSoftware Engineering Fundamentals
- Concurrency Control For In-Memory Financial State