Concurrency in Rust
In Rust, a data race is a compile error, not a bug you find in production. Two marker traits, Send and Sync, tell the compiler which values may move to another thread and which may be shared. With Arc you share ownership, with Mutex and RwLock you change shared data safely, and with channels you send work between threads. The compiler does not stop deadlocks, so you still need simple lock rules.
Author: bezzad
Contents
The problem: one phone, two buyers
Our online shop has a flash sale. Only one phone is left. Two buyers click “Buy” at the same moment, and two threads run this logic:
- Read the stock. Both threads see 1.
- Charge the customer. Both pay.
- Write the stock minus one. Both write 0.
Now two people paid for one phone. This is a data race: two threads use the same memory at the same time, at least one of them writes, and nothing orders the accesses. In C++ or Java this code compiles. In Rust, the version without a lock does not compile. Let us see why.
Starting a thread
use std::thread;
fn main() {
let order_ids = vec![101, 102, 103];
let handle = thread::spawn(move || {
for id in &order_ids {
println!("sending invoice for order {id}");
}
order_ids.len()
});
let sent = handle.join().expect("invoice thread panicked");
println!("{sent} invoices sent");
}
- The move keyword moves order_ids into the closure. The new thread now owns the vector.
- The new thread may live longer than main’s local variables. So the spawn function only accepts closures that own their data (the ’static bound). A plain borrow of a local variable is rejected.
- The join method waits for the thread and returns its result. It returns an Err if the thread panicked, so a panic does not get lost silently.
Send and Sync: the two marker traits
The compiler knows which types are safe to use from other threads through two marker traits. They have no methods. The compiler adds them automatically when all fields of a type have them.
- Send: a value of this type may be moved to another thread.
- Sync: a value of this type may be shared between threads through a shared reference. In exact words: a type is Sync when a shared reference to it is Send.
The spawn function requires its closure to be Send. So if you try to move a non-Send value into a thread, you get a compile error.
- Rc is neither Send nor Sync. Its reference count is a plain number. Two threads changing it at the same time could free the value too early.
- Arc is the thread-safe Rc. Its count is changed with atomic CPU instructions. It is Send and Sync when the value inside is Send and Sync.
- RefCell is Send but not Sync. You may move it to another thread, but two threads must not use it at once, because its borrow check is not atomic.
- Mutex makes a Send value Sync. Only one thread at a time can reach the data, so sharing becomes safe.
- The guard of a std Mutex is not Send. On some platforms a lock must be released by the same thread that took it.
Shared state: Arc plus Mutex
To share the stock between threads, we need two things: shared ownership (Arc) and safe changes (Mutex).
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let start = HashMap::from([("phone-x".to_string(), 1u32)]);
let stock = Arc::new(Mutex::new(start));
let mut buyers = Vec::new();
for buyer in 0..2 {
let stock = Arc::clone(&stock); // one more owner, same data
buyers.push(thread::spawn(move || {
let mut stock = stock.lock().unwrap();
match stock.get_mut("phone-x") {
Some(count) if *count > 0 => {
// check and change under the same lock
*count -= 1;
println!("buyer {buyer} got the phone");
}
_ => println!("buyer {buyer}: sold out"),
}
})); // the guard is dropped here, so the lock is released
}
for b in buyers {
b.join().unwrap();
}
}
- The data lives inside the Mutex. You cannot reach the HashMap without calling the lock method. You cannot “forget the lock”.
- The lock method returns a guard. The guard acts like a mutable reference. When the guard is dropped, the lock is released. You never call unlock.
- The check and the change happen under the same lock. If you read the stock under one lock, release it, and then change it under a second lock, two threads can still both see 1. Rust stops data races, not logic races.
- The lock method returns a Result. It is an Err when another thread panicked while it held the lock. Rust calls this a poisoned lock, because the data may be half changed. Most code calls unwrap here on purpose, so the panic spreads instead of using broken data.
Keep the critical section short
While one thread holds the lock, all others wait. So do only the small, fast change inside the lock, and do slow work like network calls outside:
use std::collections::HashMap;
use std::sync::Mutex;
pub struct Shop {
stock: Mutex<HashMap<String, u32>>,
}
fn send_confirmation_email(sku: &str) {
// imagine a slow network call
println!("email: you bought {sku}");
}
impl Shop {
pub fn buy(&self, sku: &str) -> bool {
let reserved = {
let mut stock = self.stock.lock().unwrap();
match stock.get_mut(sku) {
Some(count) if *count > 0 => {
*count -= 1;
true
}
_ => false,
}
}; // the guard is dropped at the end of this block
if reserved {
send_confirmation_email(sku); // no lock is held here
}
reserved
}
}
The inner block makes the end of the lock clear. This matters even more in async code, as the async lesson shows.
Many readers: RwLock
The product catalog is read thousands of times a second and changed a few times a day. A Mutex would make readers wait for each other for no reason. An RwLock allows many readers at once, or one writer:
use std::collections::HashMap;
use std::sync::RwLock;
pub struct Catalog {
prices: RwLock<HashMap<String, u64>>,
}
impl Catalog {
pub fn price(&self, sku: &str) -> Option<u64> {
self.prices.read().unwrap().get(sku).copied()
}
pub fn set_price(&self, sku: &str, cents: u64) {
self.prices.write().unwrap().insert(sku.to_string(), cents);
}
}
- It is the same rule as borrowing, but checked at run time: many shared readers or one writer.
- It is not always faster. An RwLock costs more per call than a Mutex. Measure before you switch.
- Never ask for the write lock while you hold a read lock in the same thread. The write lock waits for all readers, including you, so it can block forever. The documentation also says it might panic.
Simple counters: atomics
For one number, like “orders placed today”, a lock is too much. Atomic types change a value with one CPU instruction:
use std::sync::atomic::{AtomicU64, Ordering};
static ORDERS_PLACED: AtomicU64 = AtomicU64::new(0);
pub fn on_order_placed() {
ORDERS_PLACED.fetch_add(1, Ordering::Relaxed);
}
The Relaxed ordering is enough for a counter that nothing else depends on. When an atomic guards other data (for example a “ready” flag), you need stronger orderings like Acquire and Release. If you are not sure, use a Mutex.
Channels: share memory by sending messages
Instead of many threads changing shared data, you can give the work to one thread through a channel. The standard library has mpsc: multiple producers, single consumer.
use std::sync::mpsc;
use std::thread;
struct Order {
id: u64,
}
fn main() {
// bounded: at most 100 orders can wait
let (tx, rx) = mpsc::sync_channel::<Order>(100);
let packer = thread::spawn(move || {
for order in rx {
// the loop ends when every sender is dropped
println!("packing order {}", order.id);
}
});
for id in 1..=3 {
let tx = tx.clone();
thread::spawn(move || tx.send(Order { id }).unwrap());
}
drop(tx); // drop our own sender too, or the packer waits forever
packer.join().unwrap();
}
- Sending moves the value. After send, the producer cannot touch the order. No lock is needed.
- The loop over the receiver ends when all senders are gone. Forgetting to drop one sender is a common reason for a program that never ends.
- Prefer a bounded channel (sync_channel). With an unbounded channel, fast producers can fill the memory when the consumer is slow. A bounded channel makes producers wait. This is called backpressure.
Scoped threads: borrow without Arc
Sometimes you only want to split a job over a few threads and wait for all of them. The thread scope function lets threads borrow local data, because it promises that all of them finish before the scope ends:
use std::thread;
fn main() {
let order_totals: Vec<u64> = (1..=1000).collect();
let (left, right) = order_totals.split_at(order_totals.len() / 2);
let revenue = thread::scope(|s| {
let a = s.spawn(|| left.iter().sum::<u64>());
let b = s.spawn(|| right.iter().sum::<u64>());
a.join().unwrap() + b.join().unwrap()
}); // every scoped thread has finished here
println!("revenue: {revenue}");
}
No Arc, no clone, no move. The borrow checker knows the threads cannot outlive the vector.
Deadlocks: what Rust does not stop
“Fearless concurrency” means no data races. It does not mean no deadlocks. A deadlock is when threads wait for each other forever. The classic case is two locks taken in a different order:
use std::sync::Mutex;
pub struct Shop {
orders: Mutex<Vec<u64>>,
stock: Mutex<u32>,
}
impl Shop {
// Thread A: orders, then stock
pub fn place_order(&self, id: u64) {
let mut orders = self.orders.lock().unwrap();
let mut stock = self.stock.lock().unwrap();
*stock -= 1;
orders.push(id);
}
// Thread B: stock, then orders (the opposite order)
pub fn restock_report(&self) -> (u32, usize) {
let stock = self.stock.lock().unwrap();
let orders = self.orders.lock().unwrap();
(*stock, orders.len())
}
}
How to avoid it:
- Always take locks in the same order everywhere, for example “orders before stock”. Write the rule in a comment next to the struct.
- Hold only one lock at a time when you can. Copy what you need, release, then take the next lock.
- Put data that changes together under one Mutex. If orders and stock always change together, one struct inside one Mutex is simpler and cannot deadlock.
- Do not lock the same std Mutex twice in one thread. It is not reentrant. The documentation says the second call will not return: it may deadlock or panic.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| Rc or RefCell sent to another thread | Compile error: cannot be sent between threads safely. | Arc with Mutex or RwLock. |
| Read under one lock, change under another | Two threads both act on the old value. | Check and change under the same guard. |
| Slow work (network, disk) while holding a lock | All other threads wait. | Copy the data, release, then do the slow work. |
| Two locks taken in a different order | Deadlock under load. | One fixed lock order, or one Mutex. |
| Locking the same Mutex again in a helper | The thread blocks or panics. | Pass the guard or the data to the helper. |
| An unbounded channel with a slow consumer | Memory keeps growing. | A bounded channel for backpressure. |
| A sender that is never dropped | The receiver loop never ends. | Drop every sender when producers are done. |
Summary in 7 lines
- A data race is a compile error in Rust. Send and Sync tell the compiler what can cross threads.
- Send means the value may move to another thread. Sync means it may be shared by reference.
- Rc and RefCell stay on one thread. Arc, Mutex and RwLock are their thread-safe versions.
- The data lives inside the Mutex. The guard releases the lock when it is dropped.
- Keep critical sections short, and check and change under the same lock.
- Channels move ownership of messages. Prefer bounded channels, and scoped threads for short jobs.
- Rust does not stop deadlocks. Use one lock order, or fewer locks.