FerrousPath

Level 3 · Systems· Lesson 1 of 11 · 30 min

Threads and shared state

Fearless concurrency — spawning threads, Send and Sync, channels, Mutex, RwLock, and scoped threads.

Spawning threads

use std::thread;

fn main() {
    let handles: Vec<_> = (0..4)
        .map(|id| {
            thread::spawn(move || {
                let sum: u64 = (0..1_000_000u64).map(|n| n * id).sum();
                (id, sum)
            })
        })
        .collect();

    for h in handles {
        let (id, sum) = h.join().unwrap(); // join returns Err if the thread panicked
        println!("thread {id}: {sum}");
    }
}

thread::spawn takes a closure and returns a JoinHandle. The closure must be 'static and Send: the new thread may outlive the function that spawned it, so it cannot borrow from that function’s stack — hence move.

Send and Sync

Rust’s thread safety comes from two marker traits that the compiler implements automatically:

  • Send: a value of this type can be moved to another thread.
  • Sync: a value of this type can be shared between threads; formally, T: Sync if and only if &T: Send.

A type is Send/Sync if all its fields are. The few exceptions are exactly the types that would be unsafe to share: Rc (non-atomic count), Cell and RefCell (unsynchronised interior mutability), and raw pointers.

use std::rc::Rc;
use std::thread;

fn main() {
    let data = Rc::new(5);
    let handle = thread::spawn(move || { // ❌ error[E0277]: `Rc<i32>` cannot be sent between threads safely
        println!("{data}");
    });
    handle.join().unwrap();
}

This is the whole trick. A data race needs two threads accessing the same memory with at least one writing and no synchronisation. The borrow rules forbid aliased mutation; Send and Sync extend those rules across threads. Safe Rust cannot have data races. (It can still have deadlocks and logic races — those are not memory-safety bugs.)

Message passing

“Do not communicate by sharing memory; share memory by communicating.”

use std::sync::mpsc;
use std::thread;
use std::time::Duration;

fn main() {
    let (tx, rx) = mpsc::channel::<String>();

    for id in 0..3 {
        let tx = tx.clone();
        thread::spawn(move || {
            for step in 0..2 {
                thread::sleep(Duration::from_millis(10 * (id + 1)));
                tx.send(format!("worker {id} finished step {step}")).unwrap();
            }
        });
    }
    drop(tx); // drop the original sender so the loop below can end

    for message in rx {
        println!("{message}");
    }
}

mpsc means multiple producer, single consumer. send moves the value: once sent, the sender cannot touch it, so there is nothing to race on. The receiving loop ends when every sender has been dropped. For bounded queues with back-pressure use mpsc::sync_channel(n); for multi-consumer channels, the crossbeam-channel crate.

Shared state: Arc<Mutex<T>>

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0u64));

    let handles: Vec<_> = (0..8)
        .map(|_| {
            let counter = Arc::clone(&counter);
            thread::spawn(move || {
                for _ in 0..10_000 {
                    let mut guard = counter.lock().unwrap();
                    *guard += 1;
                } // guard dropped → lock released
            })
        })
        .collect();

    for h in handles {
        h.join().unwrap();
    }
    println!("{}", *counter.lock().unwrap());
}
  • Arc<T> is the atomically reference-counted Rc: shared ownership across threads.
  • Mutex<T> contains its data. lock() returns a guard that dereferences to the data and unlocks when dropped. There is no way to reach the data without locking.
  • lock() returns a Result because of poisoning: if a thread panics while holding the lock, later lockers are told the data may be inconsistent.

RwLock<T> allows many readers or one writer — the borrow rule again, enforced at runtime across threads. For simple counters and flags, atomics (AtomicU64, AtomicBool) avoid locking altogether; Level 4 treats them rigorously.

Deadlock

Rust does not prevent deadlocks. The classic recipe: thread A locks x then y; thread B locks y then x. Defences: always acquire locks in a consistent global order, hold them for as short a time as possible, and never call unknown code while holding one.

Scoped threads

thread::scope guarantees its threads are joined before it returns, so they can borrow from the stack:

use std::thread;

fn main() {
    let data: Vec<u64> = (1..=1_000_000).collect();
    let chunks: Vec<&[u64]> = data.chunks(250_000).collect();

    let total: u64 = thread::scope(|s| {
        let handles: Vec<_> = chunks
            .iter()
            .map(|chunk| s.spawn(move || chunk.iter().sum::<u64>()))
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).sum()
    });

    println!("{total}");
}

No Arc, no cloning: the borrow checker can see the threads end before data does.

Data parallelism with Rayon

For CPU-bound work over collections, the rayon crate turns an iterator into a parallel one with a work-stealing thread pool:

// crate: rayon
use rayon::prelude::*;

fn main() {
    let total: u64 = (1..=10_000_000u64)
        .into_par_iter()
        .filter(|n| n % 3 == 0)
        .map(|n| n * n % 1_000)
        .sum();
    println!("{total}");
}

Changing iter() to par_iter() is safe for the same reason everything above is: the closure must be Send + Sync, and the compiler checks it.

Exercises

  1. Compute a word-frequency HashMap over a large string by splitting it into four parts with thread::scope, counting each in a thread, and merging the maps.
  2. Build a pipeline with two channels: a producer sending numbers, a worker squaring them, and main printing the results.
  3. Write a program that deadlocks with two mutexes. Then fix it by ordering the locks.
  4. Replace the Mutex<u64> counter with AtomicU64 and fetch_add(1, Ordering::Relaxed). Measure both.

Check your understanding

Pick an answer to see the explanation.

  1. 1.Why can Rc<T> not be sent to another thread?

  2. 2.What does T: Sync mean?

  3. 3.How does Mutex<T> in Rust differ from a mutex in C?

Key terms in this lesson

Finished the lesson and the exercises?