Concurrency
A thread is a separate line of execution inside a program. Several threads run at the same time on different processor cores: one computes, another reads a file, a third answers the user. The price is shared memory. If two threads write to the same place at the same time without coordination, you get a data race: the result depends on how the threads happened to run, and changes from run to run. In languages without such a check, C++ for example, these bugs are hard to reproduce and find.
Rust catches data races at compile time, and it needs almost no new rules for that. Ownership and borrowing already forbid having a mutable reference at the same time as any other — which is exactly the condition for no data race. Two marker traits are added on top: Send says a value can be transferred to another thread, Sync says it can be shared between threads through a reference. thread::spawn requires Send and 'static, so an unsuitable type, such as Rc, simply does not compile.
The standard library offers two styles of work. You can pass messages over a channel and share no memory at all. Or you can share state through Arc<Mutex<T>>, and for a single number or flag — through atomic types. The guarantee is not absolute, though: the compiler does not catch a deadlock or an update lost between two atomic operations. The topic breaks concurrency down layer by layer — from thread::spawn to memory ordering.
Topic map
- Threads and join —
thread::spawnreturns aJoinHandle,joinwaits for the thread and hands back its result; oncemainreturns, threads are cut off; a panic stays in its own thread, andjoinreturnsErr; the output order of threads is not guaranteed. - Move Closures —
spawnrequires'static, so a local variable cannot be borrowed (E0373);movemoves the captured values into the thread; clone beforemoveif both sides need the data. - Channels —
mpsc::channel,sendmoves the value,recvblocks;Senderclones for several workers; a loop over theReceiverends once every sender is dropped;sync_channelbounds the buffer. - Mutex and Arc —
Arcprovides several owners with an atomic counter,Mutexlets threads reach the data one at a time; the guard releases the lock when dropped; poisoning after a panic; deadlock;RwLock. - Send and Sync — marker auto traits:
Sendmeans transferring ownership,Syncmeans sharing through&T;Rcis notSend,RefCellis notSync, soArc<RefCell<T>>does not compile (E0277);unsafe impl. - Scoped Threads —
thread::scopejoins all its threads before returning, so they may borrow local data withoutmoveandArc; mutable pieces throughchunks_mut. - Atomics —
AtomicUsizeandfetch_addchange a number in one indivisible operation;load+storeloses updates;Relaxedfor counters,ReleaseandAcquirefor publishing data,SeqCstby default.
Common mistakes and traps
| Mistake | Consequence |
|---|---|
Using a local variable in thread::spawn without move | error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function — the thread may outlive the function |
Passing an Rc to thread::spawn | error[E0277]: `Rc<i32>` cannot be sent between threads safely — the Rc counter is not atomic; you need Arc |
Wrapping a value with a RefCell inside in an Arc | error[E0277]: `RefCell<i32>` cannot be shared between threads safely — Arc gives only &T; changing data takes Arc<Mutex<T>> |
Keeping the original Sender alive after cloning it for the workers | The loop over the Receiver waits forever: the channel closes only when every sender is dropped |
Holding a MutexGuard during long work, or taking two mutexes in different orders | The other threads stand in line; with different orders — a deadlock the compiler does not catch |
Building an increment out of load and store on an atomic | The code compiles, but updates are lost — you need fetch_add or compare_exchange |
| Expecting the same output order from several threads | The order changes from run to run; you fix it with join, a channel or by sorting the results |
Why it matters in interviews
Concurrency is one of the main topics of a middle-level Rust interview: "fearless concurrency" is the language's promise, and the candidate is asked to explain what it rests on. At senior level they add the choice between channels, Mutex, RwLock and atomics, memory ordering, and diagnosing a deadlock or a poisoned mutex.
What interviewers usually check:
- Why
thread::spawnneedsmoveand why the closure must be'static. - How to share mutable state between threads and what role
ArcandMutexeach play. - What
SendandSyncmean, how they relate, and whyRcis notSendwhileArcis. - How
mpscchannels work: several senders, closing the channel, a bounded buffer. - How scoped threads differ from
thread::spawn. - When an atomic counter with
Relaxedis enough, and when you needAcquireandRelease.