Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 132 ยท Concurrency

Threads

Learn Rust threads: thread::spawn and JoinHandle, move closures, returning values, panics in threads, scoped threads, Builder names, and the Send and Sync traits.

A thread is an independent line of execution inside your program. Several threads can run at the same time on different CPU cores, or take turns on one core, so a program can compute on all cores, or keep working while another part waits for the network or disk. Threads are also where programs most often go wrong: two threads touching the same data without coordination cause data races, bugs that appear once in a thousand runs and vanish when you add a println!.

Rust's promise, often called fearless concurrency, is that safe Rust cannot contain a data race. The same ownership and borrowing rules you have already learned are what enforce it. In this lesson you will start threads, wait for them, get values back, handle panics, borrow local data with scoped threads, and meet the two marker traits Send and Sync that make the compiler's checks possible. The next lessons cover channels, Mutex and RwLock and atomics.

Our editor has one CPU and runs your program for at most 5 seconds. Threads still work, but we never rely on the order in which threads print. In this lesson, any output that could differ between runs is either avoided (we join threads and print from one place) or we say clearly that the order is not guaranteed.

Spawning a thread

std::thread::spawn takes a closure, starts a new operating-system thread that runs it, and returns a JoinHandle. Calling .join() on the handle waits for the thread to finish.

Rust Your first thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Because we join before printing the last line, the output order is guaranteed. join() returns a Result, which we unwrap here to keep the demo short (more on that in a moment).

When main returns, the whole process ends, even if other threads are still running. A thread you never join may be cut off in the middle of its work. A JoinHandle that is dropped without joining detaches the thread: it keeps running until it finishes or the program exits.

Returning a value from a thread

The closure's return value comes back through join():

Rust Getting a result out of a thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The type of handle is JoinHandle<u64>, and join() gives Result<u64, ...>. The same pattern scales to many threads: start them all first, collect the handles in a Vec, and join them one by one.

Rust Many threads, deterministic output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The threads run at the same time (or interleaved), but we print in the order of the Vec, so the output is always the same. This "spawn all, then join in order" shape is the simplest safe pattern: each thread works on its own data and returns an answer.

move closures: giving the thread its data

A spawned thread might outlive the function that created it, so it cannot borrow local variables. The compiler enforces this:

Rust A thread cannot borrow a local variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0373]: closure may outlive the current function, but it borrows `numbers`, which is owned by the current function

The help text suggests the fix: the move keyword makes the closure take ownership of the variables it uses.

Rust move transfers ownership into the thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

After the move, the thread owns numbers and label, and main can no longer use them (see Ownership). If both sides need the data, you either clone it before moving (let for_thread = numbers.clone();), share it with Arc (see Rc and Arc), or use scoped threads, shown next.

Scoped threads: borrowing without move

thread::spawn demands 'static data because the thread could live forever. Scoped threads (thread::scope, stable since Rust 1.63) fix that for the common case where you want to start threads and wait for all of them before moving on. The scope guarantees every thread finishes before it returns, so threads may borrow local variables, even mutably (but not the same data at the same time).

Rust Scoped threads borrow local data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two threads share data read-only, and each writes to its own variable. No move, no Arc, no cloning. The borrow checker still verifies that no two threads write the same variable.

A very useful application is splitting a slice into chunks that threads modify independently:

Rust Parallel work on disjoint chunks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

chunks_mut(4) hands out non-overlapping &mut [u32] slices, so each thread owns a different part and the compiler is happy: no data race is possible. (move here moves the reference chunk into the closure.)

Prefer thread::scope whenever the work is "fork, do something, join". Use plain spawn when threads must outlive the function, such as a background worker or server.

When a thread panics

A panic in a spawned thread does not crash the program. The thread unwinds, and join() returns Err carrying the panic payload. That is why join returns a Result.

Rust A panic stays inside its thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The panic message is also printed to stderr by the default panic hook (you will see it under the output, with the thread name, here <unnamed>) with the text index out of bounds: the len is 0 but the index is 3. Your own handling then decides what to do: retry, report, or propagate with .unwrap() (which panics main). Note that if a thread panics while holding a Mutex, the lock becomes poisoned; we cover that in Mutex and RwLock.

Naming threads and the Builder

thread::Builder lets you set a name (it appears in panic messages and debuggers) and the stack size. Its spawn returns an io::Result, because the operating system might refuse to create a thread. The plain thread::spawn panics in that case.

Rust Named threads with Builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Do not print thread::current().id(): thread ids are not stable between runs. A name is the right way to identify threads in logs.

Do threads really run in parallel?

On a multicore machine, yes. thread::available_parallelism() tells you how many threads can run at once, a good default for the size of a worker pool. (Our editor has a single CPU, so we do not print it.) Spawning a thread costs roughly the same as starting a small task in the operating system: tens of microseconds and some memory for the stack (2 MiB of virtual address space by default on Linux). That is cheap enough for dozens or a few thousand threads, but not for one thread per tiny job. For many small tasks, use a fixed number of workers fed by a channel, or a library like rayon.

Timing never determines correctness. Code that "works because thread A is usually faster" is broken. If one thread needs another's result, join it or use a channel; do not guess with sleep.

Rust Order is not guaranteed (any order is valid)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Send and Sync: why the compiler can check threads

How does the compiler know that a closure is safe to run on another thread? Through two marker traits with no methods, which the compiler implements automatically for types made of safe parts:

  • Send: a value of this type can be moved to another thread.
  • Sync: a type is Sync if &T is Send, meaning it is safe for several threads to hold shared references to it at once.

thread::spawn requires the closure (and so everything it captures) to be Send + 'static. Most types are both. The notable exceptions are types that use non-atomic reference counting or interior mutability without locks:

  • Rc<T> is neither Send nor Sync: its counter is not atomic, so two threads cloning it could corrupt the count. Use Arc<T>.
  • RefCell<T> and Cell<T> are Send (if T is) but not Sync: their runtime checks are not thread-safe. Use Mutex<T> or RwLock<T>.
  • Raw pointers are neither, until you promise otherwise with unsafe impl.
Rust Rc cannot cross threads (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0277]: `Rc<i32>` cannot be sent between threads safely

The note under it says the trait Send is not implemented for Rc<i32>. The fix is a one-word change, and it shows how little code the guarantee costs you:

Rust Arc is the thread-safe Rc

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Each thread gets its own Arc pointing at the same vector (read-only). When a thread ends, its Arc is dropped and the count goes down again. To let threads modify shared data, combine Arc with a Mutex, covered next.

Patterns and pitfalls

  • Share nothing when you can. Give each thread its own data and combine the results with join: no locks, no contention.
  • Do not detach silently. If you drop a JoinHandle, you will not see its panic or its result. Join, or send results through a channel.
  • Do not hold a thread for tiny jobs. Spawning 100,000 threads exhausts memory. Use a pool of workers.
  • Beware println! interleaving. Each println! locks stdout, so a whole line prints atomically, but lines from different threads appear in unpredictable order.
  • Panics are per thread. A background worker that panics silently dies unless something joins it.
  • A thread is not free of 'static. If a closure complains about lifetimes, the usual answers are move, Arc, or thread::scope.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does handle.join() return for a JoinHandle<u32>?

    join waits for the thread and returns Ok(value) if it finished normally, or Err(payload) if it panicked.
  2. 2. Why does thread::spawn(|| println!("{v:?}")) fail to compile when v is a local Vec?

    spawn requires a 'static closure. Borrowing a local violates that, so you use move, share with Arc, or use thread::scope.
  3. 3. What is the main advantage of thread::scope over thread::spawn?

    The scope joins all threads before returning, so references to locals cannot dangle. That lets you skip move, Arc and cloning.
  4. 4. Which type is NOT Send?

    Rc uses a non-atomic reference count, so moving clones to different threads could corrupt it. Arc is the atomic, thread-safe version.
  5. 5. A spawned thread panics and its handle is joined with .join(). What does the main thread see?

    A panic unwinds only the panicking thread. join returns Err(payload), so the caller can report it, retry, or call unwrap to propagate.

Summary

  • thread::spawn(closure) starts an OS thread and returns a JoinHandle<T>; join() waits and yields Result<T, ...>.
  • Spawned closures must be 'static + Send: use move to transfer ownership, Arc to share, or thread::scope to borrow safely.
  • A panic is contained in its thread and shows up as Err from join.
  • thread::Builder names threads and sets the stack size, and returns an io::Result.
  • Send and Sync are automatic marker traits that let the compiler reject data races; Rc, RefCell and raw pointers do not qualify.
  • Make output deterministic by joining and printing in one place; never depend on scheduling order or sleeps.

Next: Message Passing with Channels