Threads, Channels & Mutex in Rust

From the Rust cheat sheet ยท Concurrency ยท verified Jul 2026

Threads, Channels & Mutex

Spawn threads, pass messages, and share state safely.

rust
use std::thread;
use std::sync::mpsc;

// Spawn a thread
let handle = thread::spawn(|| {
    println!("Hello from a thread!");
});
handle.join().unwrap();

// Channel โ€” message passing
let (tx, rx) = mpsc::channel();
thread::spawn(move || { tx.send("hello").unwrap(); });
let msg = rx.recv().unwrap();
๐Ÿ’ก Arc<Mutex<T>> is the standard pattern for shared mutable state across threads
โšก Channels (mpsc) are for message passing; Mutex is for shared state โ€” pick one paradigm
๐Ÿ“Œ Mutex::lock() returns a MutexGuard โ€” it auto-unlocks when the guard is dropped
๐ŸŸข Send + Sync traits are auto-implemented โ€” the compiler prevents unsafe sharing at compile time
threadschannelsmutexarcconcurrency
Back to the full Rust cheat sheet