Chapter 12 of 16 · Part III, Concurrency and systems
Fearless concurrency is a claim the type system makes
How Send and Sync turn data races into compile errors, plus Arc, Mutex, poisoning, scoped threads, channels and Rayon, compared with lock, Task and PLINQ in C#.
You will use ownership and borrowing to understand what can cross a thread boundary and what can be shared. Start with Send, Sync, and the mutex example. The atomic-count measurements and parallel iterator comparison can wait until you have a working threaded program.
This is where ownership pays a dividend that is hard to appreciate until you have shipped something.
The distinction matters more than it sounds. In C#, a torn long on a 32-bit runtime and a lost update on a Dictionary are both "threading bugs" in the postmortem, but they are different animals. The torn read is the machine doing something the language never promised. The lost update is the machine faithfully executing a program whose logic was wrong. Rust draws a hard line between the two: the first category is what the compiler refuses to let you write, and the second is still entirely yours.
In C#, nothing stops you sharing a List<T> across threads. The compiler does not know or care. If you forget the lock, you find out in production, intermittently, on the busiest day. The entire System.Collections.Concurrent namespace exists because the language cannot tell you when you needed it.
Rust makes the first mistake a compile error, and it does it with two traits that have no methods at all.
Send and Sync, and why they are only marker traits
Send means a value can be moved to another thread. Sync means a reference to it can be shared with another thread. The standard library states the second one as an equation: a type T is Sync if and only if &T is Send.
Four relationships fall out of that, and they are worth memorizing, because nearly every confusing error in this area is one of them wearing a costume.
| This is true | when this is true |
|---|---|
&T is Send | T is Sync |
&mut T is Send | T is Send |
&T and &mut T are Sync | T is Sync |
Arc<T> is Send | T is Send and Sync |
The third row surprises people. A &mut T is Sync, because a mutable reference reached through a shared reference is read-only anyway. The fourth row is the one that actually bites, and it turns up two examples from now.
That closure rule is the one doing the real work. A closure is a struct you did not write, whose fields are its captures, so when you hand a closure to thread::spawn the compiler is doing exactly the same field-by-field walk it would do on any struct. If one capture is not Send, the closure is not Send, and the call does not compile.
Rc<T> is the canonical failure, because its reference count is a plain integer. Two threads incrementing it can lose an increment, the count drops to zero while a handle is still live, and you have a use-after-free. So the standard library states it outright, with impl<T: ?Sized, A: Allocator> !Send for Rc<T, A>, a negative implementation that overrides the structural rule. That is belt and braces: Rc holds a NonNull, which carries a negative Send impl of its own, so the answer would be no either way. The comment on the matching !Sync impl says why it is spelled out anyway, which is documentation and better error messages. Try to move one across a thread boundary:
use std::rc::Rc;
use std::thread;
fn main() {
let counts = Rc::new(vec![1, 2, 3]);
let handle = thread::spawn(move || {
println!("{:?}", counts);
});
handle.join().unwrap();
}
error[E0277]: `Rc<Vec<i32>>` cannot be sent between threads safely
--> src/main.rs:7:32
|
7 | let handle = thread::spawn(move || {
| ------------- ^------
| | |
| __________________|_____________within this `{closure@src/main.rs:7:32: 7:39}`
| | |
| | required by a bound introduced by this call
8 | | println!("{:?}", counts);
9 | | });
| |_____^ `Rc<Vec<i32>>` cannot be sent between threads safely
|
= help: within `{closure@src/main.rs:7:32: 7:39}`, the trait `Send` is not implemented for `Rc<Vec<i32>>`
note: required because it's used within this closure
note: required by a bound in `spawn`
|
128 | F: Send + 'static,
| ^^^^ required by this bound in `spawn`
Read the last three lines, because they are the whole idea. The rule is not baked into the compiler as a special case for threads. It is a where clause on an ordinary generic function that you could have written yourself: thread::spawn requires F: FnOnce() -> T, F: Send + 'static and T: Send + 'static. The standard library writes that Send bound on a line of its own, which is why the note can put a caret under exactly that clause instead of the whole where block. The compiler noticed that a type whose reference count is a plain integer failed a bound, and it stopped you. Not a lint, not a warning, not a runtime assertion. The program does not build.
The fix is Arc<T>, the atomically counted version.
Now the sequel, which is where the fourth row of that table earns its keep. Arc makes shared ownership thread safe. It does not make the thing inside thread safe. Wrap the RefCell from the previous chapter in an Arc and the compiler is not fooled:
use std::cell::RefCell;
use std::sync::Arc;
use std::thread;
fn main() {
let shared = Arc::new(RefCell::new(0));
let s = Arc::clone(&shared);
thread::spawn(move || {
*s.borrow_mut() += 1;
});
}
error[E0277]: `RefCell<i32>` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `RefCell<i32>`
= note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead
= note: required for `Arc<RefCell<i32>>` to implement `Send`
RefCell tracks its borrow count with a plain integer too, so it is not Sync, so Arc<RefCell<i32>> is not Send, so the closure is not Send. Three deductions, one error, and the compiler names the replacement in the note. That is a much better afternoon than the C# version of the same story, which is a Dictionary that has quietly stopped being a valid hash table.
One more that is worth knowing early: std::sync::MutexGuard<T> is Sync when T: Sync, but deliberately not Send. On some platforms a lock must be released by the thread that took it, so the guard is pinned to its thread. It matters far more for async than for threads, and the async chapter picks that up.
What the atomic count costs
The Rust Book says atomics come with a performance penalty and leaves it there. On x86-64 the penalty for a clone is one instruction prefix. Compile two functions that do nothing but clone, one an Rc and one an Arc, in release mode, and rustc emits this:
clone_arc:
mov rax, qword ptr [rdi]
lock inc qword ptr [rax]
jle .LBB8_2
ret
clone_rc:
mov rax, qword ptr [rdi]
inc qword ptr [rax]
je .LBB9_1
ret
lock inc instead of inc. That prefix is not free, because it forces the cache line holding the count into exclusive state on the executing core, so if eight threads are cloning the same Arc in a tight loop they are all fighting over one cache line. But it is also not the disaster people imagine when they read "atomic operation."
The interesting cost is on the other end. The Rustonomicon's walkthrough of Arc explains why the clone can use Relaxed ordering: incrementing the count does not publish any data, so no happens-before relationship is needed. The drop is different. It decrements with Release, and the thread that sees the count hit zero issues an Acquire fence before running the destructor, so that every write any other thread made through its handle happens-before the deallocation. That fence sits behind the branch only the last drop takes, and on x86-64 it emits no instruction at all, because loads on that architecture already have acquire semantics. On a weaker memory model such as AArch64 it becomes a real barrier instruction. Either way the common case, a clone and a drop that is not the last one, stays cheap.
The practical advice that follows: clone an Arc once per thread, not once per item. If you find yourself writing Arc::clone inside a hot loop, you almost certainly wanted to pass &Arc<T>, or better, &T, and let deref coercion do it. And if a program ever leaks enough clones to push the strong count past isize::MAX, Arc aborts the process rather than let the count wrap, which is the standard library choosing a crash over a use-after-free.
The lock owns the data
C#'s lock protects a region of code and trusts you to only touch the shared state inside it. Here is the shape you have written a hundred times, with the mistake sitting right next to the correct version:
public sealed class LogTotals
{
private readonly System.Threading.Lock _gate = new();
private readonly Dictionary<int, long> _byStatus = new();
private long _bytes;
public void Record(int status, long bytes)
{
lock (_gate)
{
_byStatus.TryGetValue(status, out var n);
_byStatus[status] = n + 1;
_bytes += bytes;
}
}
// Someone adds this six months later, in a hurry.
public void RecordFast(int status, long bytes)
{
_byStatus.TryGetValue(status, out var n);
_byStatus[status] = n + 1;
_bytes += bytes;
}
public long Bytes => _bytes;
}
Both methods compile. On .NET 9 or later that class builds with zero warnings, and RecordFast is a Dictionary corruption waiting for enough concurrent traffic to trigger a resize. The association between _gate and the two fields it protects lives in a comment, or in the head of whoever wrote it, or nowhere.
C# has been improving the edges of this. .NET 9 added System.Threading.Lock, a dedicated type, and the C# 13 compiler recognizes it in a lock statement and lowers it to EnterScope() in a using, instead of the older Monitor.Enter and try/finally pair around an arbitrary object. The compiler will even warn you if you cast a known Lock to something else and lock on that. Those are real improvements. None of them connects the lock to the data.
Rust puts the data inside the lock, so there is no second place to put it:
use std::collections::HashMap;
use std::sync::Mutex;
#[derive(Default)]
struct Inner {
by_status: HashMap<u16, u64>,
bytes: u64,
}
pub struct LogTotals {
inner: Mutex<Inner>,
}
impl LogTotals {
pub fn record(&self, status: u16, bytes: u64) {
let mut guard = self.inner.lock().unwrap();
*guard.by_status.entry(status).or_insert(0) += 1;
guard.bytes += bytes;
}
}
There is no way to write record_fast. The fields are not reachable from &self at all; lock is the only thing that hands out a reference to them, and it returns a MutexGuard which implements Deref and DerefMut onto the inner value. Forgetting to take the lock stopped being a discipline problem. It became a type error.
And because the guard releases when it is dropped, there is no finally to forget and no early return that leaks the lock, including when a panic unwinds through the critical section.
That last sentence is the simplified model, and it is worth replacing with the real one, because the simplification will cost you an afternoon eventually. The guard is not released "at the end of the block." It is released when the guard value is dropped, and Rust drops values at four different moments:
- End of scope, which is the case you were thinking of.
- An explicit
drop(guard), which is how you release early without introducing a block. - End of statement, for a temporary.
*totals.lock().unwrap() += 1;never binds the guard to anything, so the lock is held for exactly that statement.let g = totals.lock().unwrap();on its own line holds it until the end of the enclosing block. - Unwind. A panic runs destructors on the way out, which is where the poisoning story starts.
The one hole is that leaking is safe in Rust. std::mem::forget(guard) compiles, is not unsafe, and leaves the mutex locked forever. Nobody does this deliberately, but it explains why the standard library can never promise "the lock is always released."
When reads dominate, RwLock<T> is the same shape with many readers or one writer. It is also the primitive people reach for too fast. The standard library documentation includes a deadlock example that is easy to write by accident: thread one takes a read lock, thread two blocks trying to take the write lock, and thread one then takes a second read lock and hangs, because on some platforms a waiting writer blocks new readers. C# names this problem out loud, which is why ReaderWriterLockSlim has an explicit LockRecursionPolicy and defaults to forbidding recursion. Rust's answer is that the policy is whatever the OS does and you should not rely on it.
My opinion, and it is only that: for a critical section measured in nanoseconds, an uncontended Mutex usually beats an RwLock, because the reader-writer bookkeeping costs more than the exclusion you saved. Reach for RwLock when readers hold the lock for a meaningful stretch, not because the word "read" appears in your method name.
Poisoning, and the honest advice
lock() returns a Result, which is the first thing that annoys people coming from C#. The reason is poisoning: if a thread panics while holding the lock, the data behind it may be halfway through an update, so the mutex records that and every later lock() returns Err.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let cache = Arc::new(Mutex::new(vec!["ready".to_string()]));
let handle = {
let cache = Arc::clone(&cache);
thread::spawn(move || {
let mut guard = cache.lock().unwrap();
guard.push("half written".to_string());
panic!("blew up mid update");
})
};
let outcome = handle.join();
println!("worker exited cleanly: {}", outcome.is_ok());
println!("mutex poisoned: {}", cache.is_poisoned());
match cache.lock() {
Ok(guard) => println!("clean read: {:?}", *guard),
Err(poisoned) => {
let guard = poisoned.into_inner();
println!("read through poison: {:?}", *guard);
}
}
cache.clear_poison();
println!("still poisoned: {}", cache.is_poisoned());
}
worker exited cleanly: false
mutex poisoned: true
read through poison: ["ready", "half written"]
still poisoned: false
That is stdout; the panic message and its backtrace hint go to stderr alongside it. Two things to take from the block. The lock was released even though the thread panicked, which is the unwind case from the list above doing its job. And the half-written value is still there, because poisoning is advisory: PoisonError::into_inner hands you the guard anyway, and clear_poison resets the flag.
Many examples write .unwrap() so a poisoned mutex causes another panic, but the service must decide whether that panic should fail a task, a thread, or the process. The panic already told you an invariant broke. Continuing to serve requests from a data structure you know is inconsistent is how a crash becomes a data corruption incident. Handle poisoning deliberately when the guarded state is genuinely rebuildable, such as a cache you can clear, and not otherwise.
Scoped threads remove the 'static bound
thread::spawn requires 'static, which reads as a strange demand until you notice what it is defending against. A spawned thread can outlive the function that created it, so any reference it captured could dangle. The compiler will not take your word that you are going to join it.
use std::thread;
fn main() {
let lines = vec!["a".to_string(), "b".to_string()];
let handle = thread::spawn(|| {
println!("{}", lines.len());
});
}
error[E0373]: closure may outlive the current function, but it borrows `lines`, which is owned by the current function
--> src/main.rs:6:32
|
6 | let handle = thread::spawn(|| {
| ^^ may outlive borrowed value `lines`
7 | println!("{}", lines.len());
| ----- `lines` is borrowed here
|
note: function requires argument type to outlive `'static`
help: to force the closure to take ownership of `lines` (and any other referenced variables), use the `move` keyword
The move keyword the help line suggests is fine when you have one thread. With four, you now need Arc around read-only data purely to satisfy a lifetime rule, which means an allocation plus an atomic increment per thread to share a Vec that was never going anywhere.
std::thread::scope, stable since Rust 1.63, removes the bound by making the guarantee structurally: every thread spawned inside the scope is joined before scope returns, so borrowing a local is provably safe. The API documentation is worth reading once for the two lifetimes involved.
This is genuinely underused. Most fan-out-and-join work in a service is scoped in shape, and if your workers only need to read the input, scoped threads let you pass &[T] and delete the Arc entirely.
Putting it together
Here is a complete program you can paste into a file and run. It shards a batch of log lines across four scoped threads, has each worker accumulate locally and merge once under a mutex, and reports per-worker summaries back over a channel. Output is deterministic because everything is sorted before printing, which is the discipline that makes concurrent code testable.
use std::collections::HashMap;
use std::sync::mpsc;
use std::sync::Mutex;
use std::thread;
#[derive(Default)]
struct Totals {
by_status: HashMap<u16, u64>,
bytes: u64,
}
impl Totals {
fn record(&mut self, status: u16, bytes: u64) {
*self.by_status.entry(status).or_insert(0) += 1;
self.bytes += bytes;
}
fn merge(&mut self, other: Totals) {
for (status, count) in other.by_status {
*self.by_status.entry(status).or_insert(0) += count;
}
self.bytes += other.bytes;
}
}
fn parse(line: &str) -> Option<(u16, u64)> {
let mut parts = line.split_whitespace();
let status = parts.nth(2)?.parse().ok()?;
let bytes = parts.next()?.parse().ok()?;
Some((status, bytes))
}
fn main() {
let lines: Vec<String> = (0..12)
.map(|i| format!("GET /item/{i} {} {}", 200 + (i % 3) * 100, 128 + i * 8))
.collect();
let totals = Mutex::new(Totals::default());
let (tx, rx) = mpsc::channel::<String>();
thread::scope(|scope| {
for (worker, chunk) in lines.chunks(3).enumerate() {
let totals = &totals; // a plain borrow, no Arc anywhere
let tx = tx.clone();
scope.spawn(move || {
let mut local = Totals::default();
for line in chunk {
if let Some((status, bytes)) = parse(line) {
local.record(status, bytes);
}
}
let summary = format!("worker {worker}: {} bytes", local.bytes);
// One lock per worker, not one per line.
let mut shared = totals.lock().unwrap();
shared.merge(local);
drop(shared);
tx.send(summary).unwrap();
});
}
drop(tx); // release the original sender, or the loop below never ends
let mut summaries: Vec<String> = rx.iter().collect();
summaries.sort();
for s in summaries {
println!("{s}");
}
});
let totals = totals.into_inner().unwrap();
let mut by_status: Vec<_> = totals.by_status.into_iter().collect();
by_status.sort();
println!("total bytes: {}", totals.bytes);
for (status, count) in by_status {
println!("status {status}: {count}");
}
}
worker 0: 408 bytes
worker 1: 480 bytes
worker 2: 552 bytes
worker 3: 624 bytes
total bytes: 2064
status 200: 4
status 300: 4
status 400: 4
Three things in there are worth naming. The workers borrow lines and totals directly, which only works because of the scope. Each worker takes the lock once, at the end, rather than once per line, which is the difference between four lock acquisitions and twelve. And into_inner() at the end consumes the mutex and hands back the value without locking, because by then the compiler knows there is exactly one owner left, so there is nobody to exclude.
Channels, and the sender you forgot to drop
The standard library ships multi-producer, single-consumer channels, and the ownership model makes them nicer than they are elsewhere: sending a value moves it, so the sender provably cannot keep using it. That is BlockingCollection<T> with the handoff checked.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
for i in 0..3 {
let tx = tx.clone();
thread::spawn(move || {
tx.send(format!("worker {i} done")).unwrap();
});
}
drop(tx); // close the last sender so the loop can end
let mut messages: Vec<String> = rx.iter().collect();
messages.sort();
for message in messages {
println!("{message}");
}
}
The drop(tx) line is the part everyone forgets, and the symptom is a hang rather than an error, which makes it worse. The channel disconnects when every sender is gone, and the original tx you cloned from is still alive in the enclosing scope. Your C# instinct here is correct and transfers directly: this is BlockingCollection<T>.CompleteAdding(), or ChannelWriter<T>.Complete(), except that Rust expresses "no more items" through the ownership system instead of a method call, so nothing reminds you.
Rayon and PLINQ
For data parallelism, rayon is what PLINQ is for you. Change iter() to par_iter() and the chain runs across a work-stealing thread pool. The FAQ describes the mechanism, which is the Cilk model: calling join(a, b) from a worker pushes b onto that worker's queue where other workers can steal it, and the worker gets on with a. The pool defaults to one thread per logical core.
What makes this safe is not rayon being clever. It is that rayon's method signatures name the bounds, and the compiler checks them like any other generic call. Try to use a Cell as a counter inside a parallel for_each:
error[E0277]: `Cell<usize>` cannot be shared between threads safely
|
= help: within `{closure@src/main.rs:11:31: 11:34}`, the trait `Sync` is not implemented for `Cell<usize>`
= note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicUsize` instead
note: required by a bound in `rayon::iter::ParallelIterator::for_each`
|
378 | OP: Fn(Self::Item) + Sync + Send,
| ^^^^ required by this bound in `ParallelIterator::for_each`
Those bounds are part of the safety argument, alongside Rayon's implementation of work scheduling and access to memory. A third-party crate got to reuse the same guarantee the standard library uses, because Send and Sync are ordinary traits and for_each is an ordinary generic function.
The C# equivalent of that mistake compiles. This builds clean, zero warnings, on .NET 9:
var seen = new Dictionary<int, int>();
lines.AsParallel().ForAll(l => seen[l.Length] = seen.GetValueOrDefault(l.Length) + 1);
Where the C# way is better
Having said all that, PLINQ does several things rayon does not, and pretending otherwise would be dishonest.
PLINQ is conservative by design. At runtime it inspects the query shape and, if it judges parallelism unlikely to pay, runs the thing sequentially. Rayon has no equivalent analysis. Its splitting is adaptive, in that a worker only really hands off the far half of a join when another worker steals it, so it does not shred a small job into thousands of tasks. But nothing decides on your behalf that the parallel version was a bad idea, and par_iter() over a short collection with a cheap closure loses to the plain loop. PLINQ also gives you AsOrdered for order preservation, WithDegreeOfParallelism, WithCancellation for a CancellationToken, and WithMergeOptions to control how partial results come back. Rayon has a global pool you can configure and per-call control that is coarser.
The gap is wider for concurrent collections. ConcurrentDictionary<TKey, TValue> and its GetOrAdd and AddOrUpdate are excellent, heavily tuned, and in the box. Rust's standard library has no equivalent; the answer is Mutex<HashMap<K, V>>, which serializes everything, or a crate like dashmap. Interlocked is more ergonomic than assembling the same operation from std::sync::atomic with explicit orderings. And .NET's cancellation story is unified in a way Rust's simply is not, because a CancellationToken threads through synchronous and asynchronous code alike.
If your workload is a request-scoped fan-out over a shared cache, C# will get you there faster and the result will be fine. The Rust argument gets strong when the shared state is complex, long-lived, and touched from many places, which is exactly where the C# convention of "remember to take the lock" degrades as the team grows.
What breaks at scale, and what the type system still will not do
The Rustonomicon is refreshingly blunt about the limits. Rust considers it "safe" to deadlock, to have a race condition, to leak memory, to overflow an integer, and, in its own words, to delete the production database.
So take the guarantee literally and no further. Two mutexes acquired in opposite order on two threads hang exactly as they would in C#, and the compiler says nothing, because neither thread is doing anything memory-unsafe. It just never finishes.
The lock ordering advice is the same advice it has always been, and it is worth writing down because it is the part no language solves. Define a total order over your locks, document it next to the type definitions, and always acquire in that order. If a code path needs two locks and you cannot establish an order, that is a design smell rather than a locking problem, and the fix is usually to merge the two pieces of state into one mutex or to split them so no path needs both. Never call into code you do not control while holding a lock, because you cannot know what it locks. And prefer to compute outside the critical section and hold the lock only for the update, which is exactly what the worked example does when each worker accumulates locally and merges once.
The logical races are also still yours. This compiles, is free of data races, and is wrong:
if counter.lock().unwrap().is_below_limit() {
counter.lock().unwrap().increment();
}
Two separate lock acquisitions. Another thread can slip between them. It does not even deadlock, because the condition of an if is a temporary scope and the first guard is dropped before the block runs, so the second lock() finds the mutex free. The type system verified both accesses were synchronized, and the program still exceeds the limit. The fix is one acquisition spanning the check and the act, and no compiler is going to tell you that.
At the scale where this starts to matter, the failure mode changes character. In a service handling meaningful traffic, the interesting problem is rarely a missing lock; it is a lock held slightly too long. A guard that stays alive because it was bound to a let at the top of a function, across an allocation, a log call, and a metrics increment, will not corrupt anything. It will serialize your whole request path, and you will see it as a p99 that degrades with concurrency while CPU sits idle and every thread is parked.
Rust's guard makes the extent of the critical section visible in the code, since the lock is held exactly as long as the guard is alive, but you still have to look. The same discipline that keeps lock blocks small in C# keeps guard scopes small in Rust, and the tools for finding the problem, sampling profilers and lock contention counters, are the ones you already know.
The other scale problem is one Rust makes easy to create: Arc<Mutex<T>> as a reflex. Every C# field that was mutable and shared becomes one, and now a structure that used to be a graph of objects is a graph of locks with no ordering discipline, which is the deadlock recipe above with more steps.
Mistakes a C# engineer makes here
Translating every shared field into Arc<Mutex<T>>. In C# a shared mutable object is the default, so the mechanical translation produces a lock per field. Recognize it when your struct has three or more Arc<Mutex<...>> members. The fix is usually one mutex around a struct that holds all three fields, which makes the invariant between them enforceable and removes any question of ordering.
Locking once per item. for line in lines { totals.lock().unwrap().record(line); } is correct and slow, and it is the direct translation of a lock inside a foreach body. Accumulate into a local and merge once.
Reaching for Arc to satisfy a lifetime. If the compiler complains about 'static on thread::spawn and the data is read-only and outlives the join, you wanted thread::scope.
Forgetting drop(tx). The symptom is a receive loop that never ends. Recognize it by the fact that nothing is logged after the last worker finishes.
Assuming Send plus Sync means correct. Those traits describe when a type is safe to transfer or share across threads. Their guarantees depend on sound implementations and do not establish application-level correctness. A program made entirely of Arc<Mutex<T>> can deadlock on its second lock and lose updates across two separate acquisitions.
Trying to use a RefCell because it worked single-threaded. The compiler will tell you, clearly, and name RwLock in the note. Take the suggestion.
Checking yourself
Why is Arc<RefCell<T>> rejected when Arc<T> is fine? Because Arc<T> is only Send when T is both Send and Sync, and RefCell is not Sync: its borrow counter is a plain integer, so two threads sharing a reference to it could race on that counter. Arc makes shared ownership thread safe, not the value inside.
A colleague says Rust prevents race conditions. What do you correct? Safe Rust prevents data races, assuming sound unsafe dependencies: conflicting concurrent accesses where at least one is a write, at least one is non-atomic, and the accesses lack the required ordering. Race conditions are timing-dependent logic bugs, and a check-then-act split across two lock acquisitions is still wrong in Rust, still compiles, and still runs.
When would you choose thread::scope over thread::spawn plus Arc? When the threads are joined before the borrowed data goes away, which is nearly every fan-out-and-join. The scope guarantees the join, so the 'static bound is not needed, and you can pass ordinary references instead of paying for an allocation and per-thread atomic increments.
Your service starts returning PoisonError from every request after one bad deploy. What happened, and what are your options? A thread panicked while holding that mutex, so the lock is flagged as guarding possibly inconsistent data. You can fail the affected operation or shut down deliberately; recover the guard with PoisonError::into_inner and repair the state; or clear the flag with clear_poison once you know the data is sound again. What you should not do is call into_inner reflexively to make the errors go away.
Get the next deep dive by email
New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.
You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.
Written by Zeeshan Adil
I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.