TExcelTAD
Home › Rust › Rust Concurrency

Rust Concurrency

Concurrency means doing several things at once, for example splitting a big calculation across CPU cores. In many languages this is where the scariest bugs live: two threads write the same memory at the same moment and the result depends on luck. Rust's ownership rules extend to threads, so a data race is a compile-time error. The Rust community calls this fearless concurrency.

Note: Threads run in an unpredictable order. To keep the examples on this page deterministic, each one waits for its threads and prints results in a fixed order.

Spawning threads

std::thread::spawn starts a new thread running a closure. It returns a JoinHandle; calling .join() waits for the thread to finish and gives back the value the closure returned.

rust · try it yourself
use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        let mut sum = 0;
        for n in 1..=100 {
            sum += n;
        }
        sum
    });

    println!("main thread keeps working...");
    let result = handle.join().unwrap();
    println!("worker computed {}", result);
}
main thread keeps working...
worker computed 5050

If you forget join, main may finish first and the whole process exits, killing the worker mid-way.

Moving data into threads

A spawned thread might outlive the function that created it, so it cannot borrow local variables. Use a move closure to transfer ownership into the thread.

rust · try it yourself
use std::thread;

fn main() {
    let chunks = vec![vec![1, 2, 3], vec![10, 20], vec![100, 200, 300]];
    let mut handles = Vec::new();

    for (id, chunk) in chunks.into_iter().enumerate() {
        handles.push(thread::spawn(move || {
            let total: i32 = chunk.iter().sum();
            (id, total)
        }));
    }

    for handle in handles {
        let (id, total) = handle.join().unwrap();
        println!("chunk {} sums to {}", id, total);
    }
}
chunk 0 sums to 6
chunk 1 sums to 30
chunk 2 sums to 600

The threads may finish in any order, but we join the handles in the order they were created, so the printed lines are always the same.

Message passing with channels

A channel is a one-way pipe: producers send values with a Sender, and a consumer receives them with a Receiver. mpsc stands for multiple producer, single consumer.

rust · try it yourself
use std::sync::mpsc;
use std::thread;

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

    let producer = thread::spawn(move || {
        for word in ["ready", "set", "go"] {
            tx.send(word.to_string()).unwrap();
        }
        // tx is dropped here, which closes the channel
    });

    producer.join().unwrap();

    for message in rx {
        println!("received: {}", message);
    }
}
received: ready
received: set
received: go

Messages from a single sender always arrive in the order they were sent. Iterating over rx ends once every Sender has been dropped.

Sharing state: Arc and Mutex

Sometimes many threads need to update the same value. Two tools work together here:

Type Role
Arc<T> Atomically reference counted — like Rc, but safe to share between threads
Mutex<T> Mutual exclusion — only one thread at a time can lock() and access the data
RwLock<T> Many readers or one writer at a time
rust · try it yourself
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = Vec::new();

    for _ in 0..8 {
        let counter = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            for _ in 0..1000 {
                let mut value = counter.lock().unwrap();
                *value += 1;
            } // lock released here each time
        }));
    }

    for h in handles {
        h.join().unwrap();
    }

    println!("final count: {}", *counter.lock().unwrap());
}
final count: 8000

Each lock() returns a guard; the lock is released automatically when the guard goes out of scope. Because every increment happens under the lock, the total is always exactly 8000.

What the compiler protects you from

Try to share a plain Rc or a mutable local between threads and the code will not compile:

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

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

The Send and Sync marker traits tell the compiler which types can safely cross thread boundaries. Rc is neither; Arc is both (when its contents are).

Tip: Prefer message passing when work can be split into independent pieces, and Arc<Mutex<T>> when threads truly need to update shared data.

Test yourself

What does calling .join() on a JoinHandle do?

  1. Starts the thread
  2. Waits for the thread to finish and returns its result
  3. Merges two threads into one
  4. Kills the thread

Which type lets several threads share ownership of the same value?

  1. Rc<T>
  2. Box<T>
  3. Arc<T>
  4. RefCell<T>

What does mpsc in std::sync::mpsc stand for?

  1. Multiple producer, single consumer
  2. Main process, sub child
  3. Mutex protected shared cell
  4. Message passing, synchronous call