Concurrency
Threads and `move`, channels, `Mutex` and `Arc`, `Send` and `Sync`, scoped threads, atomics and deadlocks.
20 questions
JuniorTheoryCommonWhat does the program print?
What does the program print?
4
Open full question →Common mistakes
- ✗Expecting
0because each thread got its own clone:Arc::cloneadds another owner of the sameMutex, so all four threads change one counter. - ✗Expecting lost updates as in a data race: the thread holds the lock from
lock()until its guard drops, so the four increments happen one after another.
Follow-up questions
- →What would the compiler say if you replaced
ArcwithRcin this program? - →Why does the program print the total only after joining every handle?
JuniorTheoryCommonWhat does the program print (lines separated by spaces)?
What does the program print (lines separated by spaces)?
1 2 3
Open full question →Common mistakes
- ✗Expecting the loop to hang after
3: the channel closes when every sender is dropped, and the onlytxmoved into the thread, which drops it when it ends. - ✗Expecting nothing because
mainhas nojoin:for x in rxblocks on each message, somainwaits for the thread through the channel itself.
Follow-up questions
- →What would happen if
mainclonedtxbefore spawning and kept the clone alive? - →How does the order change when three threads each send one number through clones of
tx?
JuniorTheoryCommonWhat are mpsc channels, and what ends a for msg in rx loop?
What are mpsc channels, and what ends a for msg in rx loop?
mpsc::channel() returns a Sender and a Receiver. send moves a value in, recv blocks until one arrives. Each producer owns a clone of the Sender, one consumer reads. for msg in rx ends once every Sender is dropped.
Common mistakes
- ✗Keeping the original
txalive inmainafter cloning it for the workers, so the loop overrxwaits forever - ✗Expecting one overall order of messages from several senders, when only each sender's own order is kept
- ✗Using a value after
send, though it has been moved into the channel (E0382)
Follow-up questions
- →How does
mpsc::sync_channel(0)differ from an ordinarychannel()? - →What do you use when several threads must take jobs from one queue?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
moveto make any value fit for a thread:movechanges how a value is captured, whileSenddecides whether it may go to another thread at all. - ✗Expecting a run-time error from the shared counter:
Sendis checked by the compiler, soRcnever reaches a second thread.
Follow-up questions
- →Which type replaces
Rchere, and what does it do differently with its count? - →Why is a
Stringcaptured the same way accepted bythread::spawn?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
[1, 2, 3]becausejoincomes right afterspawn: the compiler checks the signature ofspawn, not what happens later, and the closure must own what it uses. - ✗Expecting the closure to take
vby itself because a thread needs it: a closure borrows what it only reads, and onlymovemakes it take ownership.
Follow-up questions
- →What changes if you write
move ||, and canmainstill printvafterjoin? - →How would you give the thread its own copy while
mainkeeps the original vector?
MiddleDebuggingCommonFix an Arc<RefCell<Vec<i32>>> the compiler refuses to share between threads
Fix an Arc<RefCell<Vec<i32>>> the compiler refuses to share between threads
Arc hands each thread only &T, so the value inside must be Sync, and RefCell is not: its borrow counter is non-atomic. Replace it with Mutex and write through hits.lock().unwrap(); the program prints [0, 1, 2].
Common mistakes
- ✗Expecting
Arcto make its contents thread-safe, though it only shares them by&T - ✗Believing
RefCellis banned from threads entirely, though it isSendand only lacksSync - ✗Reaching for
unsafe impl Sync, which promises a safety the non-atomic borrow counter cannot keep
Follow-up questions
- →When would an
AtomicUsizeinside theArcreplace theMutexhere? - →Why may a
RefCellbe moved into one thread whole while it may not be shared?
MiddleDebuggingCommonFix a for value in rx loop that never ends after every worker has finished
Fix a for value in rx loop that never ends after every worker has finished
The workers drop only their clones, while the original tx stays alive in main, so the channel never closes and for value in rx keeps waiting. Call drop(tx) right after spawning the workers; the program then prints total: 60.
Common mistakes
- ✗Assuming the channel closes when the workers finish, though the original
txinmainstill counts as a live sender - ✗Adding
joincalls to fix the hang, which waits for the threads but leaves the channel open - ✗Hard-coding three
recvcalls, which hides the bug and breaks as soon as the number of workers changes
Follow-up questions
- →How would scoping
txinside a block remove the need for an explicitdrop? - →What does
sendreturn in a worker ifmainhas already droppedrx?
MiddleDesignCommonA payment service keeps each account as Arc<Mutex<Account>>. A transfer locks the source account and then the destination; a reconciliation job locks accounts in whatever order it reads them from a report. Under load, two threads now and then freeze for good: one holds account A and waits for B, the other holds B and waits for A. The compiler gave no warning. Constraints: a transfer must stay atomic across both accounts, with no moment when money has left one account but not reached the other; you may change the order in which locks are taken and how long they are held, but the accounts must stay thread-safe. Explain why this happens, which rules you would introduce to prevent deadlocks, and when a message-passing design would serve better than locks.
A payment service keeps each account as Arc<Mutex<Account>>. A transfer locks the source account and then the destination; a reconciliation job locks accounts in whatever order it reads them from a report. Under load, two threads now and then freeze for good: one holds account A and waits for B, the other holds B and waits for A. The compiler gave no warning. Constraints: a transfer must stay atomic across both accounts, with no moment when money has left one account but not reached the other; you may change the order in which locks are taken and how long they are held, but the accounts must stay thread-safe. Explain why this happens, which rules you would introduce to prevent deadlocks, and when a message-passing design would serve better than locks.
Each thread holds one lock and waits for the other, a cycle safe Rust does not catch. Lock both accounts in one global order, say by id; keep guards short, without I/O; back off with try_lock; or give one thread the accounts behind a channel.
Common mistakes
- ✗Believing safe Rust prevents deadlocks, though it rules out data races, not threads waiting on each other forever
- ✗Releasing the first lock before taking the second, which removes the deadlock but breaks the transfer's atomicity
- ✗Fixing the order only in one code path, while transfers in opposite directions still lock in opposite orders
Follow-up questions
- →How would you lock two accounts when a transfer goes from an account to itself?
- →What does a
try_lockretry loop risk under heavy contention, and how do you limit it?
MiddleCodeCommonSum a large slice on several threads with thread::scope, borrowing the slice
Sum a large slice on several threads with thread::scope, borrowing the slice
thread::scope joins all its threads before returning, so s.spawn closures may borrow data. Split it with chunks, sum each chunk in a scoped thread, add the results. thread::spawn demands 'static, forcing move or Arc.
Common mistakes
- ✗Wrapping the data in
Arcor cloning it for threads that are joined inside the same function - ✗Calling
thread::spawninstead ofs.spawninside the scope, which still demands'static - ✗Expecting a
joinright afterthread::spawnto let the closure borrow local data
Follow-up questions
- →What happens to
thread::scopewhen one of its threads panics and was not joined by hand? - →How would you let each scoped thread double the numbers of its own piece in place?
MiddleTheoryCommonWhat do Send and Sync mean, and why is Rc neither while Arc can be both?
What do Send and Sync mean, and why is Rc neither while Arc can be both?
Send means a value may move to another thread, Sync that threads may share it by &T, and T: Sync iff &T: Send. The Rc count is non-atomic, so Rc is neither. Arc<T> counts atomically and is Send + Sync only if T: Send + Sync.
Common mistakes
- ✗Swapping the two traits:
Sendis about transferring ownership to another thread,Syncabout sharing through&T - ✗Believing
Arcmakes any value thread-safe, thoughArc<RefCell<T>>is still notSend - ✗Thinking the traits are checked at run time, while they are pure type checks that cost nothing
Follow-up questions
- →Why does
thread::spawnrequire its closure to beSendbut notSync? - →How does a struct of your own become
Sendwithout any code from you?
MiddleCodeCommonRun jobs on N worker threads and collect their results over one channel
Run jobs on N worker threads and collect their results over one channel
Make one mpsc::channel, split the jobs among N threads and move a clone of tx into each to send results. Drop the original tx in the caller; rx.iter().collect() then gathers them in arrival order and ends after the last worker.
Common mistakes
- ✗Forgetting
drop(tx)in the caller, sorx.iter()waits forever after the workers finish - ✗Expecting the results in job order, though messages from different senders interleave by timing
- ✗Cloning
txonce before the loop, so the second iteration hits E0382 on the moved clone
Follow-up questions
- →How would you let idle workers pull the next job from one shared queue instead of a fixed share?
- →What would
mpsc::sync_channeladd if the caller were much slower than the workers?
SeniorDesignCommonAn HTTP service runs 32 request threads and 4 background workers, all in one process, using only the standard library. Three pieces of state need sharing: a configuration struct that every request reads and an admin endpoint replaces a few times a day; a counter of served requests that every request thread increments; and a queue of jobs that request threads produce and the 4 workers consume. Constraints: readers of the configuration must not block one another, and a reload must never expose a half-written configuration; the counter must not lose increments; when the workers fall behind, request threads must slow down instead of letting the queue grow without limit. Pick a synchronization primitive for each of the three — Arc<Mutex<T>>, RwLock, a channel or an atomic type — and defend each choice, including what it would cost to choose wrongly.
An HTTP service runs 32 request threads and 4 background workers, all in one process, using only the standard library. Three pieces of state need sharing: a configuration struct that every request reads and an admin endpoint replaces a few times a day; a counter of served requests that every request thread increments; and a queue of jobs that request threads produce and the 4 workers consume. Constraints: readers of the configuration must not block one another, and a reload must never expose a half-written configuration; the counter must not lose increments; when the workers fall behind, request threads must slow down instead of letting the queue grow without limit. Pick a synchronization primitive for each of the three — Arc<Mutex<T>>, RwLock, a channel or an atomic type — and defend each choice, including what it would cost to choose wrongly.
Config — RwLock<Arc<Config>>: readers clone the Arc, then unlock; a reload swaps it. Counter — AtomicU64::fetch_add(1, Relaxed). Queue — bounded mpsc::sync_channel, blocking senders when full; workers share Receiver via Arc<Mutex<_>>.
Common mistakes
- ✗Holding a configuration guard for a whole request, which turns every reload into a wait for all in-flight requests
- ✗Building an increment from
loadandstore, which compiles but loses updates between the two calls - ✗Using an unbounded channel for work, so a slow consumer lets the queue eat all memory with no backpressure
Follow-up questions
- →Why does
Relaxedsuffice for the counter but not for a flag that publishes the new configuration? - →Would you weigh a crate such as the lock-free pointer swap crate
arc-swapfor the config, and why?
MiddleTheoryOccasionalWhy does Mutex::lock() return a Result, and what can you do with a poisoned lock?
Why does Mutex::lock() return a Result, and what can you do with a poisoned lock?
If a thread panics while holding the guard, the mutex is poisoned: the data may be half-updated, so every later lock() returns Err(PoisonError). unwrap() passes the panic on; into_inner() on the error returns the guard to repair the data.
Common mistakes
- ✗Treating the
unwrap()afterlock()as noise, though it turns poisoning into a visible panic instead of silent work on corrupted data - ✗Believing a poisoned mutex has lost its data, while
into_inner()on thePoisonErrorstill hands back the guard - ✗Expecting
lock()to fail while another thread holds the mutex, though it blocks;try_lockis the call that does not wait
Follow-up questions
- →How do
is_poisonedandclear_poisonhelp after you have repaired the data? - →Why might a team switch to a mutex type without poisoning, and what do they give up?
SeniorTheoryOccasionalWhat do atomic memory orderings guarantee, and when is Relaxed enough?
What do atomic memory orderings guarantee, and when is Relaxed enough?
Relaxed makes only the operation itself atomic, enough for a counter. A Release store with an Acquire load makes every write before the store visible after the load, as a ready flag needs. AcqRel does both; SeqCst adds one global order.
Common mistakes
- ✗Putting
Relaxedon a flag that publishes other data, so the reader may see the flag before the data - ✗Testing ordering bugs only on x86, whose strong memory model hides reorderings that ARM exposes
- ✗Believing
SeqCstmakes aloadfollowed by astoreone indivisible step, though onlyfetch_*orcompare_exchangedo
Follow-up questions
- →Why does dropping an
ArcuseReleaseon the decrement and anAcquirefence before freeing? - →How would the model checker crate
loomhelp you test code that uses these orderings?
SeniorDebuggingOccasionalDiagnose a service that hangs under load and then reports poisoned-mutex errors
Diagnose a service that hangs under load and then reports poisoned-mutex errors
Workers 1 and 3 each hold one stock lock and wait for the other, since transfer_stock locks in argument order. Separately, worker 2 panicked while holding a guard and poisoned that mutex. Lock pairs by index; check stock before changing it.
Common mistakes
- ✗Reading the two symptoms as one bug, though the hang is a lock-order cycle and the poison comes from a separate panic
- ✗Silencing poisoning with
into_inner()everywhere, which hides half-updated data instead of fixing the panic that caused it - ✗Expecting
try_lockto skip the poison check, though it returnsTryLockError::Poisonedjust aslockreturns an error
Follow-up questions
- →How does the lock crate
parking_lothelp find such cycles with its deadlock detection feature? - →What happens in your fix when
fromandtoname the same item?
SeniorDebuggingOccasionalFix a spawned closure that is rejected because it captures a type that is not Send
Fix a spawned closure that is rejected because it captures a type that is not Send
Report holds an Rc<str>, so it is not Send and cannot move into the thread (E0277). Move only Send inputs, the title as a String, build the Report inside the closure and return the rendered String; the Rc never crosses threads.
Common mistakes
- ✗Reaching for
Arc<Mutex<T>>by reflex when the value never needs to be shared, only built on the right thread - ✗Believing a fresh clone of an
Rc-holding value becomesSend, though the type, not the instance, decides - ✗Silencing E0277 with
unsafe impl Send, which promises a thread safety the non-atomic count cannot keep
Follow-up questions
- →How would you keep the
Reporton one thread and feed it lines from several workers instead? - →Why is a
RefCellmoved into a thread whole accepted while anRcis not?
SeniorTheoryOccasionalWhich types are Send but not Sync, or the reverse, and why does RwLock<T> need T: Sync?
Which types are Send but not Sync, or the reverse, and why does RwLock<T> need T: Sync?
Cell<T> and RefCell<T> are Send but not Sync: they may move whole, not be shared. MutexGuard<T> is Sync but not Send: the locking thread must unlock. RwLock gives many readers &T at once, so T must be Sync; Mutex gives one.
Common mistakes
- ✗Believing
RefCellis banned from threads entirely, though it isSendand only sharing it is refused - ✗Expecting
Mutex<T>to beSyncfor anyT, though it still needsT: Sendbecause the value moves between the threads that lock it - ✗Assuming
RwLockandMutexhave the same bounds, though concurrent readers makeRwLockrequireT: Syncas well
Follow-up questions
- →Why are raw pointers neither
SendnorSync, and what doesunsafe impl Sendpromise? - →How does
Mutex<RefCell<T>>becomeSynceven thoughRefCell<T>is not?
SeniorDesignOccasionalAn audio thread produces sample frames and a single mixer thread consumes them. You are to design a lock-free single-producer single-consumer ring buffer between them. Constraints: capacity is fixed at construction and is a power of two; no locks and no allocation after construction; the producer must never block — when the buffer is full it reports that and drops the frame; the consumer must never read a slot before the producer has finished writing it, and the producer must never overwrite a slot the consumer is still reading; the code must be correct on ARM as well as on x86. Describe who owns the head and tail indices, which atomic memory orderings each load and store uses and why, why you place head and tail on separate cache lines, and how you would test the buffer.
An audio thread produces sample frames and a single mixer thread consumes them. You are to design a lock-free single-producer single-consumer ring buffer between them. Constraints: capacity is fixed at construction and is a power of two; no locks and no allocation after construction; the producer must never block — when the buffer is full it reports that and drops the frame; the consumer must never read a slot before the producer has finished writing it, and the producer must never overwrite a slot the consumer is still reading; the code must be correct on ARM as well as on x86. Describe who owns the head and tail indices, which atomic memory orderings each load and store uses and why, why you place head and tail on separate cache lines, and how you would test the buffer.
Only the producer writes tail, only the consumer head. Each reads the other's index with Acquire and stores its own with Release after using the slot. Pad both onto separate cache lines against false sharing; test with loom and stress runs.
Common mistakes
- ✗Using
Relaxedon the index store that publishes a slot, so the other thread may see the new index before the slot's data - ✗Leaving
headandtailin one cache line, so the two cores keep stealing that line from each other on every update - ✗Trusting tests on x86 alone, whose strong memory model hides the reorderings that break the buffer on ARM
Follow-up questions
- →Why does a power-of-two capacity let you replace the modulo with a bit mask?
- →How does caching the other thread's index locally cut the number of
Acquireloads?
SeniorDesignOccasionalA profile service answers each lookup in about 200 ms, so you put an in-memory LRU cache in front of it, shared by 64 request threads in one process. About 95% of requests are hits. Constraints: the cache holds at most one million entries and evicts the least recently used one; a hit must update the entry's recency; a miss must not stop other threads from reading or loading unrelated keys while its 200 ms load runs; and when many threads miss on the same key at once, the slow service should be called only once for it. Design the cache: choose between one Mutex, one RwLock and sharding, describe how eviction and lock granularity work, and explain how a lookup avoids holding a lock during the slow load.
A profile service answers each lookup in about 200 ms, so you put an in-memory LRU cache in front of it, shared by 64 request threads in one process. About 95% of requests are hits. Constraints: the cache holds at most one million entries and evicts the least recently used one; a hit must update the entry's recency; a miss must not stop other threads from reading or loading unrelated keys while its 200 ms load runs; and when many threads miss on the same key at once, the slow service should be called only once for it. Design the cache: choose between one Mutex, one RwLock and sharding, describe how eviction and lock granularity work, and explain how a lookup avoids holding a lock during the slow load.
Shard by key hash into N Mutex<LruShard>: an LRU hit moves the entry, so it writes and RwLock gains nothing. Hold a shard lock only to look up or insert; on a miss release it, load, insert, with a per-key in-flight marker for one load.
Common mistakes
- ✗Choosing
RwLockfor an LRU cache, though every hit reorders the recency list and needs exclusive access - ✗Holding a lock across the slow load, so every key behind that lock waits 200 ms for one miss
- ✗Releasing the lock on a miss with no in-flight marker, so a burst of misses on one key calls the service many times
Follow-up questions
- →How would you pick the number of shards, and what happens to LRU accuracy as it grows?
- →How would a waiting thread learn that another thread's load for its key failed?