skip to content

OS Threads and Locks

Rust's type system makes data races a compile error through Send and Sync. Interviewers test spawning, Arc with Mutex, channels, atomics and data parallelism.

on this pageshow

explore

questions

page 1 of 2

In Rust's std::sync::mpsc, what happens to a value when a thread sends it, and how does another thread receive it?

level: juniorimportance: must knowfreq 80%

answer

  1. ownership, not copying
  2. send takes T by value
  3. use after send fails to compile
  4. recv blocks; for loop ends on disconnect

basics

~20 s

Sender::send takes the value by value, so ownership moves into the channel and any later use is error E0382. The receiving thread calls recv, which blocks until a message arrives, or loops with for msg in rx.

solid answer

~30 s

`mpsc::channel()` returns a `Sender<T>` and a `Receiver<T>`. `tx.send(value)` takes `T` by value, so the value moves into the channel: the sender can no longer use it, and touching it afterwards is E0382, "borrow of moved value". Nothing is cloned; a `String` crosses threads by handing over its buffer. On the other side `rx.recv()` blocks while the queue is empty and a `Sender` is alive, then returns `Ok(value)` and the receiver owns it. `for msg in rx` repeats `recv()` and ends once every `Sender` has been dropped and the queue is drained. Messages from one sender arrive in the order sent.

code

rust · 19 lines
rust
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel::<String>();
    let decoder = thread::spawn(move || {
        for i in 1..=3 {
            let frame = format!("frame-{i:03}.png");
            tx.send(frame).unwrap(); // ownership of the String moves into the channel
        }
        // tx is dropped here, when the closure returns
    });
    for frame in rx {
        // blocks on each recv; ends once every Sender is gone
        println!("resize {frame}");
    }
    decoder.join().unwrap();
    println!("pipeline done");
}

go deeper

for a junior

Recall the pair from mpsc::channel, that send moves the value so a later use is E0382, and that recv blocks until something arrives.

for a middle

Explain why move semantics make message passing safe without a lock, and that a for loop over the Receiver ends only when every Sender is gone.

for a senior

Show you handle the Result from send instead of unwrapping by reflex, and that you pick explicit clones or Arc when both sides need the data.

for a principal

Frame ownership transfer as the design property: data owned by one stage at a time, so a reviewer checks hand-offs rather than lock discipline.

## What a channel is in Rust's standard library `std::sync::mpsc` (multi-producer, single-consumer) is the standard library's way to move values from one thread to another. Calling `mpsc::channel()` returns a pair: a **`Sender<T>`** (by convention `tx`) and a **`Receiver<T>`** (`rx`). Both are ordinary owned values: you move the `Sender` into a worker thread's `move` closure, keep the `Receiver` where the results are consumed, and the two halves stay connected through a shared queue. The element type `T` is fixed for the channel, and it is inferred from the first `send` when you do not write it out (`mpsc::channel::<String>()` spells it explicitly). To move a `Sender<T>` into a spawned thread, `T` must be `Send`; why some types are not is covered in the lesson on `Send` and `Sync`. ## `send` moves the value into the channel `Sender::send` has the signature `fn send(&self, t: T) -> Result<(), SendError<T>>`. The parameter is `T` **by value**, so a call is a **move**: - After `tx.send(frame)`, the sending thread no longer owns `frame`. Using it again is a compile error, **E0382** ("borrow of moved value"), exactly as with any other function that takes ownership. - Nothing is copied or cloned behind your back. A `String` or a `Vec<u8>` crosses threads by handing over its heap buffer, which is why channels are cheap for large values. - If the sender needs to keep a copy, it calls `.clone()` explicitly before sending, or sends something cheap to share such as an `Arc`. This is the property that makes message passing safe without locks: at any moment exactly one thread owns each value, and the compiler enforces it. The sender cannot mutate a frame after handing it over, because it no longer has a name for it. ```rust let frame = String::from("frame-001.png"); tx.send(frame).unwrap(); println!("sent {frame}"); // error[E0382]: borrow of moved value: `frame` ``` The usual fixes are to log before sending, or to send and log a cheap derived value (a length, an id) computed before the move. ## How the receiving thread gets values The `Receiver` offers several ways to take messages; the everyday one is blocking: 1. **`rx.recv()`** blocks the current thread while the queue is empty and at least one `Sender` (clones included) is still alive. When a message arrives it returns `Ok(value)`, and the receiving thread now owns it. 2. When every `Sender` has been dropped, `recv()` still hands out whatever was already queued, and only after the queue is empty returns **`Err(RecvError)`**: no more messages can ever arrive. 3. **`for msg in rx`** (or `for msg in &rx`, or `rx.iter()`) wraps that loop. `Receiver<T>` implements `IntoIterator`, and each step calls `recv()` and stops at the first `Err`. So the loop ends exactly when the channel is drained and disconnected; it never panics. Messages from one `Sender` arrive in the order they were sent (the docs promise first-in, first-out order); messages from several senders interleave in whatever order the sends happened. ## The three-stage image pipeline, first link | Step | Call | Ownership | |---|---|---| | decoder creates a frame | `let frame = ...` | decoder thread owns it | | decoder sends | `tx.send(frame)` | the channel owns it | | resizer receives | `rx.recv()` or `for frame in rx` | resizer thread owns it | | decoder finishes | closure returns, `tx` drops | resizer sees the end after draining the queue | In the runnable example, the decoder thread sends three `String`s and returns, which drops its `Sender`. The main thread's `for frame in rx` prints all three and then ends, because the only `Sender` is gone. Without that drop the loop would wait for ever, which is the most common channel bug and the subject of the question on disconnection. ## Points to say out loud in an interview - `send` takes ownership; a use after `send` is E0382, not a runtime surprise. - `recv` blocks; `try_recv` and `recv_timeout` are the non-blocking and bounded-wait variants. - A `for` loop over a `Receiver` ends when every `Sender` is dropped and the queue is empty. - The standard channel is single-consumer: the `Receiver` is not `Clone`, so one thread (or one owner) receives. - `send` returns a `Result` because the `Receiver` may already be gone; `unwrap()` there turns a dead consumer into a panic in the producer.

  • The decoder wants to log each frame after sending it. How do you keep that working?
    Log before the `send`, or compute what you need first (`let name_len = frame.len();`) and use that after the move. If the full value is really needed on both sides, clone it explicitly before sending or send an `Arc<T>` so both threads share one allocation; `send` itself never copies.
  • Why does `send` return a `Result` at all on an unbounded channel?
    Because the `Receiver` may already have been dropped. `send` then returns `Err(SendError(value))`, handing the value back, since it could never be received. An `Ok` only means the receiving half still existed at that moment; it does not prove the message will be read.
  • What is the difference between `for msg in rx` and `for msg in &rx`?
    Both block on each message and stop when the channel is drained and disconnected. `for msg in rx` consumes the `Receiver` (its `IntoIterator` impl takes it by value), so `rx` is unusable afterwards; `for msg in &rx` borrows it through `Receiver::iter`, so you can still call `try_recv` or iterate again later.

  • Says send copies or clones the value into the channel.
  • Thinks the sender can still read a value after sending it.
  • Believes recv returns immediately with an error when the queue is empty.
  • Expects a for loop over a Receiver to stop when the queue is momentarily empty.
  • Assumes several threads can each hold and read the same std Receiver.
open as a page

In Rust, why do request threads sharing a rate limiter's `HashMap` need `Arc<Mutex<HashMap<String, u32>>>` instead of a plain `Arc<HashMap<String, u32>>`?

level: juniorimportance: must knowfreq 80%

basics

~10 s

Arc only shares ownership: every thread gets a &HashMap, so insert fails with E0596. Mutex adds exclusive access: lock() turns &Mutex into a MutexGuard that derefs mutably and unlocks when dropped.

open as a page

In Rust, what do the `Send` and `Sync` marker traits each promise, and who implements them for your own structs?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Send means a value may be moved to another thread; Sync means &T may be shared across threads, so T: Sync exactly when &T: Send. Both are auto traits that rustc implements for a struct whose fields all implement them.

open as a page

In Rust, what does `std::thread::spawn` return, and what happens to the spawned thread if `main` returns without joining it?

level: juniorimportance: must knowfreq 80%

basics

~20 s

thread::spawn returns a JoinHandle<T> for the closure's result; join() waits and gives Ok(T) or an Err carrying the panic payload. Dropping the handle detaches the thread, and once main returns the process exits, stopping any thread still running.

open as a page

In Rust, why is `Ordering::Relaxed` enough for a shared `AtomicUsize` request counter, and is the total read after `join` exact?

level: middleimportance: must knowfreq 55%

basics

~20 s

Relaxed still makes each fetch_add one indivisible read-modify-write, so no increment is lost; it only drops ordering with other memory. JoinHandle::join makes every thread operation happen-before it returns, so the total read after joining is exact.

open as a page

With Rust's std::sync::mpsc, why can a receive loop hang after every worker finishes, and what do send, recv, try_recv and recv_timeout report on disconnection?

level: middleimportance: must knowfreq 65%

basics

~20 s

A std Receiver only sees disconnection when every Sender, including the original kept in main, is dropped; until then recv blocks. recv then returns RecvError, try_recv and recv_timeout distinguish empty from disconnected, and send returns SendError with the value.

open as a page

In Rust, why does calling `m.lock()` again inside a `match m.lock().unwrap().get(id)` arm hang, and how do you end the `MutexGuard` sooner?

level: middleimportance: must knowfreq 65%

basics

~20 s

A temporary MutexGuard in a match scrutinee lives until the match ends, so every arm holds the lock and relocking on that thread never returns. Copy the value out in a separate let, or drop a named guard.

open as a page

In a Rust log-compaction tool, how does `std::thread::scope` let four worker threads borrow chunks of a local `Vec<Record>`, and what does it guarantee?

level: middleimportance: must knowfreq 65%

basics

~20 s

std::thread::scope, stable since Rust 1.63, joins every thread spawned on its Scope before it returns, so those threads may borrow locals such as slices of a Vec. The borrow checker still applies: many shared borrows, or one mutable borrow, per value.

open as a page

In Rust, one thread boxes a `Config` and stores its pointer in a static `AtomicPtr<Config>` for reader threads; which orderings make that safe, and what goes wrong with `Relaxed`?

level: seniorimportance: must knowfreq 50%

basics

~20 s

Store the pointer with Ordering::Release and load it with Ordering::Acquire, so a reader that sees the pointer also sees the writes that built the Config. With Relaxed, reading those fields is a data race, which is undefined behaviour.

open as a page

In Rust, why can a `static REQUESTS: AtomicUsize` be incremented from many threads without `static mut`, `unsafe` or a `Mutex`?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Atomic methods such as fetch_add take &self, not &mut self, so an immutable static can be updated through them; AtomicUsize is Sync, and AtomicUsize::new is a const fn, so it can initialise a static directly.

open as a page

In Rust with Rayon, how do `par_iter`, `par_iter_mut` and `into_par_iter` parallelise an iterator chain, and what does each one borrow?

level: juniorimportance: should knowfreq 50%

basics

~20 s

Rayon's par_iter, par_iter_mut and into_par_iter replace iter, iter_mut and into_iter, returning a ParallelIterator that splits items across a global thread pool. They yield &T (needs T: Sync), &mut T or owned T (both need T: Send).

open as a page

In Rust's std::sync::mpsc, how does sync_channel(n) differ from channel(), and what does sync_channel(0) do?

level: middleimportance: should knowfreq 50%

basics

~20 s

channel() is unbounded: Sender::send never waits and the queue can grow without limit. sync_channel(n) has a fixed buffer, so SyncSender::send blocks when it is full, giving back-pressure. sync_channel(0) is a rendezvous: each send waits for a matching recv.

open as a page

In Rust, what happens to a `std::sync::Mutex` when a thread panics while holding its guard, and how can other threads still recover the data?

level: middleimportance: should knowfreq 50%

basics

~20 s

Unwinding drops the guard, which unlocks the mutex but marks it poisoned, so later lock() calls return Err(PoisonError). The error still holds the guard: into_inner() recovers it, and clear_poison(), stable since Rust 1.77, resets the flag.

open as a page

In Rust, how does `rayon::join` let a recursive quicksort sort both halves in parallel, and why does it need no `'static` or `Arc`?

level: middleimportance: should knowfreq 40%

basics

~20 s

rayon::join runs closure A on the current worker and offers closure B for an idle worker to steal, returning both results. It blocks until both finish, so closures need only Send and may borrow disjoint halves from split_at_mut.

open as a page

With Rayon in Rust, which results keep sequential order across `collect`, `for_each`, `reduce` and `sum`, and what must a `reduce` operation satisfy?

level: middleimportance: should knowfreq 35%

basics

~20 s

Rayon's collect into a Vec keeps input order, but for_each side effects run in any order. reduce and sum combine pieces in an unspecified grouping, so the operation must be associative and the identity closure a true identity.

open as a page

In Rust, why does moving an `Arc<mpsc::Receiver<u64>>` clone into `thread::spawn` fail with E0277, while `Arc<Mutex<Receiver<u64>>>` compiles?

level: middleimportance: should knowfreq 55%

basics

~20 s

Arc<T> is Send only when T: Send + Sync, because its clones hand &T to many threads. mpsc::Receiver is Send but not Sync, so Arc<Receiver> is not Send; Mutex<T> is Sync whenever T: Send, which repairs it.

open as a page

In Rust, when should you start worker threads with `std::thread::Builder` rather than `thread::spawn`, and how does `available_parallelism` help decide how many?

level: middleimportance: should knowfreq 35%

basics

~20 s

Use thread::Builder to name a thread, set its stack size, or handle a failed spawn as an io::Error instead of a panic. thread::available_parallelism() returns io::Result<NonZero<usize>>, an estimate of usable parallelism that can fail and should be given a fallback.

open as a page

In Rust, how does a `thread_local!` static behave: when is each thread's copy created and dropped, and why is it read through `with`?

level: middleimportance: should knowfreq 35%

basics

~20 s

A thread_local! static gives each thread its own copy, built on that thread's first access and dropped, best effort, at thread exit. LocalKey::with lends a &T inside a closure so it cannot outlive the thread; mutation needs Cell or RefCell.

open as a page

In Rust, when do you use `compare_exchange_weak` instead of `compare_exchange` on an `AtomicUsize`, and what do the `try_update` and `update` methods add?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Use compare_exchange_weak inside a retry loop, where a spurious failure just costs one more iteration and may compile to cheaper code; use compare_exchange for a one-shot attempt. try_update and update, stable since Rust 1.95, wrap that loop around a closure.

open as a page

In Rust, how do you write a toy spin lock on an `AtomicBool`, and which orderings do its acquire and release steps need?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Pair an AtomicBool with an UnsafeCell<T>; lock by winning compare_exchange_weak(false, true, Acquire, Relaxed) in a loop that calls hint::spin_loop, and unlock with store(false, Release). Relaxed on either step lets critical sections overlap, which is a data race.

open as a page

In Rust, why can't four worker threads share one std::sync::mpsc::Receiver, and when would you switch to crossbeam-channel instead?

level: seniorimportance: should knowfreq 40%

basics

~20 s

std's Receiver is not Clone and not Sync, so it cannot be shared and Arc<Receiver> fails with E0277. Use Arc<Mutex<Receiver>> for a std-only fix, or crossbeam-channel, whose Receiver is Clone and which adds select! over several channels.

open as a page

In Rust, how does a request thread block on `std::sync::Condvar` until a rate-limit bucket has tokens, and why must the wait sit in a loop?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Lock the token count, then call Condvar::wait with the guard: it unlocks, sleeps and relocks before returning. Because std allows spurious wakeups and other waiters may take the token, recheck the count in a while loop or use wait_while.

open as a page

In Rust, when does replacing a `Mutex` with `std::sync::RwLock` actually help, and what does std promise about waiting writers and a thread calling `read()` twice?

level: seniorimportance: should knowfreq 45%

basics

~20 s

RwLock helps only for read-mostly data with substantial read sections, and it needs T: Send + Sync. std promises no priority policy, so a waiting writer may block new readers, and a second read() on the same thread can deadlock.

open as a page

In Rust, why do Rayon's `for_each` and `map` demand `Fn + Sync + Send` closures, and why is locking a `Mutex` per item the wrong fix?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Rayon calls one closure concurrently from many workers, so it must be Fn (no mutating captures, else E0594) and Sync (shareable captures, else E0277). A per-item Mutex compiles but serialises the loop; fold plus reduce needs no lock.

open as a page

A Rust job reads 2 million files and hashes them with `par_iter` on Rayon's global pool; why does it stall on slow storage, and how do you reconfigure Rayon?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Rayon's global pool has one worker per logical CPU and adds none when one blocks, so file reads park workers and idle the CPUs. Read files outside Rayon, or run that stage in its own ThreadPool via install.

open as a page

Why is Rust's `std::sync::MutexGuard` never `Send`, though a `&MutexGuard<T>` may cross threads when `T: Sync`, and what does that rule out?

level: seniorimportance: should knowfreq 40%

basics

~20 s

std writes impl !Send for MutexGuard because some platforms, POSIX threads among them, require a mutex to be unlocked by the thread that locked it. The guard is Sync when T: Sync, since &MutexGuard only yields &T.

open as a page

A Rust metrics library wraps a C handle as `*mut c_void`; when is `unsafe impl Send` justified, and what would `unsafe impl Sync` add?

level: seniorimportance: should knowfreq 45%

basics

~20 s

unsafe impl Send is justified when the C library allows a handle to be used and freed off its creating thread and the wrapper owns it exclusively; unsafe impl Sync also promises that concurrent &self calls are safe.

open as a page

In Rust, how does a worker thread's panic surface differently under `thread::spawn` and under `thread::scope`, and how do you read the panic message?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A panic unwinds only its own thread. Under thread::spawn it reaches you as Err(payload) from join, or not at all. Under thread::scope an explicit join also gives Err, but an unjoined panic makes scope panic once all threads end.

open as a page

As a Rust lead, what code-review rule do you set for hand-written atomics and orderings weaker than `SeqCst`, and when do you require `Mutex`, `OnceLock` or a channel instead?

level: principalimportance: should knowfreq 22%

basics

~20 s

Allow Relaxed for independent counters in safe code, require std primitives for anything that publishes or guards data, and confine hand-written orderings that guard unsafe access to one reviewed module with documented Release/Acquire pairs and Miri tests.

open as a page

Designing a Rust image pipeline with decode, resize and encode threads, when do you connect stages by channels rather than share state through Arc<Mutex<T>>?

level: principalimportance: should knowfreq 35%

basics

~20 s

Use channels when data flows one way through stages: each image is moved, bounded sync_channel links cap memory, and dropping senders shuts stages down in turn. Use shared state for read-mostly lookups, aggregates and random access that every thread needs.

open as a page

showing 1–30 of 32