Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 12 · Concurrency & async

    12.1Threads, channels & shared state

    How to run work on several threads in Rust, pass messages between them, share data safely, and why a data race doesn't compile.

    About 30 minutesIntermediate

    On this page
    1. Concept map
    2. Spawning a thread and getting its result
    3. Why move?
    4. Borrowing from the stack with scoped threads
    5. Channels: passing messages
    6. Shared state: Arc<Mutex<T>>
    7. Sharing isn’t the same as changing
    8. RwLock: many readers or one writer
    9. Atomics for counters and flags
    10. Which one should I use?
    11. Under the hood
    12. Common pitfalls
    13. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Start a threadnew Worker(file) from node:worker_threadsnew Thread(...), or Task.Run(...) on the thread poolstd::thread::spawn(move || ...), which returns a JoinHandle<T>
    Wait for its resultListen for the worker's message eventthread.Join(), or await taskhandle.join(), which returns the closure's value (or the panic)
    Let threads read a local variableNot possible; each worker gets a copyLambdas capture it; the GC keeps it alivestd::thread::scope: threads borrow it, and the scope waits for them
    Pass messages between threadspostMessage and the message eventChannel<T>, BlockingCollection<T>std::sync::mpsc::channel(): sending moves the value
    Change shared data from several threadsNumbers in a SharedArrayBuffer, with Atomicslock, Interlocked, ConcurrentDictionaryArc<Mutex<T>>, RwLock<T>, atomics such as AtomicU64
    Two threads changing one variable without a lockNot possible with ordinary objects: workers don't share themCompiles, and loses updates at run timeCompile error

    In TypeScript, real parallelism means worker threads: each worker has its own heap, and you pass it copies of your data as messages. Nothing is shared unless you use a SharedArrayBuffer.In C#, any thread can touch any object. Thread, Task.Run, lock, Channel<T> and the concurrent collections give you the tools, and it’s up to you to use them everywhere they’re needed. Rust threads share memory like threads in Java or C++C# threads, but the compiler checks every piece of data a thread touches. Why Rust showed the short version: a racing counter doesn’t compile, and a Mutex fixes it. This lesson covers the full toolkit: spawning and joining threads, borrowing from the stack with scoped threads, channels, and shared state with Arc, Mutex, RwLock and atomics.

    Spawning a thread and getting its result

    Here’s a sum split into two halves, each computed on its own thread. The main thread waits for both results and prints them in a fixed order.

    TypeScript
    sum.ts
    import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
    
    function sumRange(start: number, end: number): number {
      let total = 0;
      for (let n = start; n < end; n++) {
        total += n;
      }
      return total;
    }
    
    if (isMainThread) {
      const ranges = [
        [0, 500],
        [500, 1000],
      ];
      // Each worker runs this same file on a new thread.
      const parts = await Promise.all(
        ranges.map(
          (range) =>
            new Promise<number>((resolve, reject) => {
              const worker = new Worker(new URL(import.meta.url), { workerData: range });
              worker.once("message", resolve);
              worker.once("error", reject);
            }),
        ),
      );
      parts.forEach((part, i) => console.log(`part ${i}: ${part}`));
      console.log(`total: ${parts.reduce((sum, part) => sum + part, 0)}`);
    } else {
      const [start, end] = workerData as [number, number];
      parentPort?.postMessage(sumRange(start, end));
    }
    C#
    Sum.cs
    (int Start, int End)[] ranges = [(0, 500), (500, 1000)];
    var tasks = ranges.Select(range => Task.Run(() => SumRange(range.Start, range.End)));
    var parts = await Task.WhenAll(tasks);
    for (var i = 0; i < parts.Length; i++)
    {
        Console.WriteLine($"part {i}: {parts[i]}");
    }
    Console.WriteLine($"total: {parts.Sum()}");
    
    static long SumRange(int start, int end)
    {
        long total = 0;
        for (var n = start; n < end; n++)
        {
            total += n;
        }
        return total;
    }
    Rust
    use std::thread;
    
    fn sum_range(start: u64, end: u64) -> u64 {
        (start..end).sum()
    }
    
    fn main() {
        let ranges = [(0, 500), (500, 1000)];
        let handles: Vec<_> = ranges
            .into_iter()
            .map(|(start, end)| thread::spawn(move || sum_range(start, end)))
            .collect();
        let parts: Vec<u64> = handles
            .into_iter()
            .map(|handle| handle.join().unwrap())
            .collect();
        for (i, part) in parts.iter().enumerate() {
            println!("part {i}: {part}");
        }
        println!("total: {}", parts.iter().sum::<u64>());
    }

    Output

    part 0: 124750
    part 1: 374750
    total: 499500
    • thread::spawn takes a closure and starts an operating-system thread to run it. Unlike a worker, it doesn’t need a separate file or a message to get started: the closure is the thread’s code, and it can use any function in your program.It’s closest to new Thread(...).Start(): a real OS thread, not a thread-pool work item. Unlike Thread, it can return a value.
    • It returns a JoinHandle<u64>. handle.join() waits for the thread to finish and gives back the closure’s return value, much like awaiting the worker's messageawait task.
    • join() returns a Result: Ok(value), or Err if the thread panicked. .unwrap() passes that panic on to the main thread. Result and ? covers Result.

    Because the results are collected in the order the threads were spawned, the output is the same every run, however the threads are scheduled.

    Why move?

    The closure starts with move. Leave it out and Rust refuses:

    use std::thread;
    
    fn main() {
        let name = String::from("worker");
        let handle = thread::spawn(|| println!("hello from {name}"));
        handle.join().unwrap();
    }

    Rust doesn't compile this: error E0373

    error[E0373]: closure may outlive the current function, but it borrows `name`, which is owned by the current function
     --> main.rs:5:32
      |
    5 |     let handle = thread::spawn(|| println!("hello from {name}"));
      |                                ^^                       ---- `name` is borrowed here
      |                                |
      |                                may outlive borrowed value `name`
      |
    note: function requires argument type to outlive `'static`
     --> main.rs:5:18
      |
    5 |     let handle = thread::spawn(|| println!("hello from {name}"));
      |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    help: to force the closure to take ownership of `name` (and any other referenced variables), use the `move` keyword
      |
    5 |     let handle = thread::spawn(move || println!("hello from {name}"));
      |                                ++++

    A closure normally borrows the variables it uses. But a spawned thread can outlive the function that started it: nothing forces main to call join. If the thread borrowed name and main returned first, the thread would read a dropped String. So thread::spawn only accepts closures that own everything they use, and move makes the closure take ownership of name (or a copy, for Copy values like start and end above). TypeScriptC# never asks this question, because a worker can’t see your variables at alla lambda’s captured variables live on the heap, and the garbage collector keeps them alive as long as the thread needs them. Closures covers move in detail.

    Borrowing from the stack with scoped threads

    move is fine for small values, but often you want several threads to read one big piece of data without copying it. That’s what thread::scope is for: threads spawned inside it may borrow local variables, because the scope doesn’t return until every one of them has finished.

    TypeScript
    logs.ts
    import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
    
    function countErrors(lines: string[]): number {
      return lines.filter((line) => line.startsWith("ERROR")).length;
    }
    
    if (isMainThread) {
      const logs = ["ERROR disk", "INFO start", "ERROR slow", "INFO done"];
      const halves = [logs.slice(0, 2), logs.slice(2)];
      // workerData is copied into each worker, so the workers never see `logs` itself.
      const counts = await Promise.all(
        halves.map(
          (half) =>
            new Promise<number>((resolve, reject) => {
              const worker = new Worker(new URL(import.meta.url), { workerData: half });
              worker.once("message", resolve);
              worker.once("error", reject);
            }),
        ),
      );
      console.log(`errors: ${counts.reduce((sum, count) => sum + count, 0)}`);
      console.log(`still have ${logs.length} lines`);
    } else {
      parentPort?.postMessage(countErrors(workerData as string[]));
    }
    C#
    Logs.cs
    string[] logs = ["ERROR disk", "INFO start", "ERROR slow", "INFO done"];
    // The lambdas share `logs` itself; the GC keeps it alive while any task needs it.
    var counts = await Task.WhenAll(
        Task.Run(() => CountErrors(new ArraySegment<string>(logs, 0, 2))),
        Task.Run(() => CountErrors(new ArraySegment<string>(logs, 2, 2))));
    Console.WriteLine($"errors: {counts.Sum()}");
    Console.WriteLine($"still have {logs.Length} lines");
    
    static int CountErrors(ArraySegment<string> lines) => lines.Count(line => line.StartsWith("ERROR"));
    Rust
    use std::thread;
    
    fn count_errors(lines: &[&str]) -> usize {
        lines
            .iter()
            .filter(|line| line.starts_with("ERROR"))
            .count()
    }
    
    fn main() {
        let logs = ["ERROR disk", "INFO start", "ERROR slow", "INFO done"];
        let errors: usize = thread::scope(|s| {
            let handles: Vec<_> = logs
                .chunks(2)
                .map(|half| s.spawn(move || count_errors(half)))
                .collect();
            handles
                .into_iter()
                .map(|handle| handle.join().unwrap())
                .sum()
        });
        println!("errors: {errors}");
        println!("still have {} lines", logs.len());
    }

    Output

    errors: 2
    still have 4 lines

    logs.chunks(2) gives two slices, &[&str], that point into the array. Each thread borrows one. The move here moves the slice reference into the closure, not the lines themselves: nothing is copied. When the closure passed to thread::scope ends, any thread you didn’t join is joined automatically, and only then does scope return. So by the time main prints logs.len(), no thread can still be using it, and the borrow checker can prove it.

    Mental model shiftThreads can borrow

    Workers never share ordinary data, so passing data to one means copying it.In C#, sharing data with a thread means sharing a heap object, kept alive by the garbage collector. A scoped Rust thread can take a plain & reference to a local variable, just like a function call can. No copy, no reference counting, no garbage collector: the scope guarantees the threads end before the data does. Reach for thread::scope first whenever the threads’ work ends before your function returns.

    Channels: passing messages

    A channel is a queue between threads: one side sends, the other receives. std::sync::mpsc stands for multiple producer, single consumer: you can clone the sender as often as you like, but there’s one receiver. Here three threads each count the words in a document and send back the result:

    TypeScript
    words.ts
    import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
    
    type WordCount = { id: number; count: number };
    
    if (isMainThread) {
      const documents = ["the quick brown fox", "hello world", "one two three"];
      const results: WordCount[] = [];
      await Promise.all(
        documents.map(
          (text, id) =>
            new Promise<void>((resolve, reject) => {
              const worker = new Worker(new URL(import.meta.url), { workerData: { id, text } });
              worker.once("message", (result: WordCount) => {
                results.push(result);
                resolve();
              });
              worker.once("error", reject);
            }),
        ),
      );
      // Messages arrive in whatever order the workers finish.
      results.sort((a, b) => a.id - b.id);
      for (const { id, count } of results) {
        console.log(`doc ${id}: ${count} words`);
      }
    } else {
      const { id, text } = workerData as { id: number; text: string };
      parentPort?.postMessage({ id, count: text.split(" ").length } satisfies WordCount);
    }
    C#
    Words.cs
    using System.Threading.Channels;
    
    string[] documents = ["the quick brown fox", "hello world", "one two three"];
    var channel = Channel.CreateUnbounded<(int Id, int Count)>();
    var writers = documents.Select((text, id) =>
        Task.Run(() => channel.Writer.TryWrite((id, text.Split(' ').Length))));
    await Task.WhenAll(writers);
    channel.Writer.Complete(); // no more messages: ends the read loop below
    
    var results = new List<(int Id, int Count)>();
    await foreach (var result in channel.Reader.ReadAllAsync())
    {
        results.Add(result);
    }
    // Messages arrive in whatever order the tasks finish.
    foreach (var (id, count) in results.OrderBy(result => result.Id))
    {
        Console.WriteLine($"doc {id}: {count} words");
    }
    Rust
    use std::sync::mpsc;
    use std::thread;
    
    fn main() {
        let documents = vec!["the quick brown fox", "hello world", "one two three"];
    
        let (tx, rx) = mpsc::channel();
        for (id, text) in documents.into_iter().enumerate() {
            let tx = tx.clone();
            thread::spawn(move || {
                tx.send((id, text.split_whitespace().count())).unwrap();
            });
        }
        drop(tx); // only the threads' clones are left
    
        let mut results: Vec<(usize, usize)> = rx.iter().collect();
        // Messages arrive in whatever order the threads finish.
        results.sort();
        for (id, count) in results {
            println!("doc {id}: {count} words");
        }
    }

    Output

    doc 0: 4 words
    doc 1: 2 words
    doc 2: 3 words
    • mpsc::channel() returns a pair: a Sender (tx) and a Receiver (rx). The element type, (usize, usize), is inferred from what’s sent.
    • Each thread gets its own clone of the sender. This is where Rust differs from Channel<T>: there’s no Complete() call. The channel closes when every Sender has been dropped. That’s why main drops its own tx: otherwise rx.iter() would wait forever for a message from a sender that’s still alive.
    • rx.iter() (or for message in rx) receives until the channel closes. rx.recv() receives one message, and returns Err once the channel is closed and empty.
    • mpsc::channel() is unbounded. mpsc::sync_channel(n) holds at most n messages, so a fast sender waits for a slow receiver, like Channel.CreateBounded<T>(n).

    The threads here aren’t joined: the loop over rx is what waits, because each thread sends its message before it ends. (The handles from thread::spawn are simply dropped, which detaches the threads.)

    Sending a value moves it into the channel. A worker’s postMessage copies the data (a structured clone), so the sender keeps its own copy.In C#, the sender keeps a reference to the object it wrote and can still change it while the reader uses it. In Rust, the sender gives it up:

    use std::sync::mpsc;
    
    fn main() {
        let (tx, rx) = mpsc::channel();
        let report = String::from("done");
        tx.send(report).unwrap();
        println!("{report}");
        println!("{}", rx.recv().unwrap());
    }

    Rust doesn't compile this: error E0382

    error[E0382]: borrow of moved value: `report`
     --> main.rs:7:16
      |
    5 |     let report = String::from("done");
      |         ------ move occurs because `report` has type `String`, which does not implement the `Copy` trait
    6 |     tx.send(report).unwrap();
      |             ------ value moved here
    7 |     println!("{report}");
      |                ^^^^^^ value borrowed here after move
      |
      = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
    help: consider cloning the value if the performance cost is acceptable
      |
    6 |     tx.send(report.clone()).unwrap();
      |                   ++++++++

    The String now belongs to whoever receives it. Nothing is copied, and two threads can never touch it at the same time, because only one of them owns it.

    Shared state: Arc<Mutex<T>>

    Sometimes threads really do need to change the same data. Here four threads each record 1,000 hits on one shared counter:

    TypeScript
    hits.ts
    import { Worker, isMainThread, workerData } from "node:worker_threads";
    
    if (isMainThread) {
      // Only raw bytes can be shared between workers.
      const hits = new Int32Array(new SharedArrayBuffer(4));
      const workers = Array.from({ length: 4 }, () => new Worker(new URL(import.meta.url), { workerData: hits }));
      await Promise.all(workers.map((worker) => new Promise((resolve) => worker.once("exit", resolve))));
      console.log(`hits: ${Atomics.load(hits, 0)}`);
    } else {
      const hits = workerData as Int32Array;
      for (let i = 0; i < 1000; i++) {
        Atomics.add(hits, 0, 1);
      }
    }
    C#
    Hits.cs
    var hits = 0;
    var gate = new Lock();
    var threads = Enumerable.Range(0, 4)
        .Select(_ => new Thread(() =>
        {
            for (var i = 0; i < 1000; i++)
            {
                lock (gate)
                {
                    hits++;
                }
            }
        }))
        .ToList();
    threads.ForEach(thread => thread.Start());
    threads.ForEach(thread => thread.Join());
    Console.WriteLine($"hits: {hits}");
    Rust
    use std::sync::{Arc, Mutex};
    use std::thread;
    
    fn main() {
        let hits = Arc::new(Mutex::new(0));
        let mut handles = Vec::new();
        for _ in 0..4 {
            let hits = Arc::clone(&hits);
            handles.push(thread::spawn(move || {
                for _ in 0..1000 {
                    *hits.lock().unwrap() += 1;
                }
            }));
        }
        for handle in handles {
            handle.join().unwrap();
        }
        println!("hits: {}", *hits.lock().unwrap());
    }

    Output

    hits: 4000

    Two types work together here:

    • Mutex<T> owns the data. The only way to reach the counter is hits.lock(), which waits for the lock and returns a MutexGuard: a smart pointer you use like &mut i32. The lock is released when the guard is dropped, here at the end of the statement. Compare C#‘s lock (gate): the compiler has no idea that gate protects hits, so a hits++ somewhere else without the lock compiles fine.Shared memory in TypeScript is just bytes, and Atomics is the only safe way to change them; Rust’s Mutex works for any type, from a number to a HashMap.
    • Arc<T> (atomically reference-counted) lets several threads own the same Mutex. thread::spawn needs closures that own their data, so each thread gets its own Arc, all pointing at one allocation. Arc::clone copies the pointer and adds one to the count; the data is freed when the last Arc is dropped. Shared ownership covers reference counting.

    lock() returns a Result because a mutex is poisoned if a thread panics while holding it: the data might be half-updated. .unwrap() turns that into a panic in the next thread too, which is the usual choice.

    With thread::scope you wouldn’t need the Arc at all: scoped threads can borrow a plain Mutex, as the counter in Why Rust does. Arc is for threads that aren’t scoped.

    Sharing isn’t the same as changing

    Arc alone gives shared ownership, and in Rust, shared means read-only. Forget the Mutex and the race is a compile error:

    use std::sync::Arc;
    use std::thread;
    
    fn main() {
        let hits = Arc::new(0);
        let worker_hits = Arc::clone(&hits);
        let handle = thread::spawn(move || *worker_hits += 1);
        handle.join().unwrap();
    }

    Rust doesn't compile this: error E0594

    error[E0594]: cannot assign to data in an `Arc`
     --> main.rs:7:40
      |
    7 |     let handle = thread::spawn(move || *worker_hits += 1);
      |                                        ^^^^^^^^^^^^^^^^^ cannot assign
      |
      = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Arc<i32>`

    Arc<T> hands out &T, never &mut T, so *worker_hits += 1 has nothing to write through. To change shared data, the Arc has to hold something that allows changes through a shared reference safely: a Mutex, an RwLock or an atomic. The next lesson, Send & Sync, shows how the compiler knows which types those are.

    RwLock: many readers or one writer

    A Mutex lets one thread in at a time, even if all of them only read. RwLock<T> allows any number of readers at once, or one writer: the borrowing rule from References, enforced at run time.

    use std::sync::RwLock;
    use std::thread;
    
    fn main() {
        let config = RwLock::new(String::from("v1"));
        let bytes_read: usize = thread::scope(|s| {
            let readers: Vec<_> = (0..3)
                .map(|_| s.spawn(|| config.read().unwrap().len()))
                .collect();
            s.spawn(|| *config.write().unwrap() = String::from("v2"));
            readers
                .into_iter()
                .map(|reader| reader.join().unwrap())
                .sum()
        });
        println!("{bytes_read} bytes read");
        println!("config: {}", config.read().unwrap());
    }

    Output

    6 bytes read
    config: v2

    read() returns a guard you use like &String; write() returns one you use like &mut String. Each reader sees "v1" or "v2", depending on timing, but both are two bytes long, so the total is always 6. It’s the same idea as ReaderWriterLockSlim, with the data inside the lock. Use it for data that’s read often and changed rarely, like configuration; for short critical sections, a Mutex is usually as fast and simpler.

    Atomics for counters and flags

    For a single number or flag, a lock is more than you need. Atomic types, such as AtomicU64, AtomicUsize and AtomicBool, change their value with one CPU instruction, through a shared reference:

    use std::sync::atomic::{AtomicU64, Ordering};
    use std::thread;
    
    fn main() {
        let hits = AtomicU64::new(0);
        thread::scope(|s| {
            for _ in 0..4 {
                s.spawn(|| {
                    for _ in 0..1000 {
                        hits.fetch_add(1, Ordering::Relaxed);
                    }
                });
            }
        });
        println!("hits: {}", hits.load(Ordering::Relaxed));
    }

    Output

    hits: 4000

    fetch_add is Atomics.add, and load is Atomics.load.fetch_add is Interlocked.Add, and load reads the current value. The Ordering argument says what other memory the operation synchronizes. Relaxed is enough for a counter that nothing else depends on; if one thread sets a flag to say “the data is ready”, use Release to set it and Acquire to read it. When in doubt, SeqCst is the strictest and simplest to reason about.

    Which one should I use?

    WhatWhenWhyHow
    thread::scopeThe threads’ work ends before your function returns: split a job, wait for all the parts. The default.Threads borrow local data with plain references. No Arc, no move of big values, and every thread is joined for you.thread::scope(|s| { s.spawn(|| work(&data)); })
    thread::spawnA thread that runs on its own, possibly longer than the function that started it: a background worker, a listener.Its closure owns everything it uses, so it can outlive its caller.let handle = thread::spawn(move || ...); then handle.join()
    mpsc::channelThreads produce results or jobs for another thread.Each value has one owner at a time, so nothing is shared and nothing needs a lock.let (tx, rx) = mpsc::channel(); clone tx per producer, drop the original, then for msg in rx
    Mutex<T> (in Arc for spawned threads)Several threads change the same data.The data can only be reached by locking, so you can’t forget the lock.Arc::new(Mutex::new(map)), then *data.lock().unwrap() = ...
    RwLock<T>Data that many threads read and few change.Readers don’t block each other.config.read().unwrap(), config.write().unwrap()
    Atomics (AtomicU64, AtomicBool)One counter, flag or ID shared between threads.No lock: one instruction per update.hits.fetch_add(1, Ordering::Relaxed)

    Rule of thumb: use thread::scope when the work finishes before your function returns, and thread::spawn with move when it doesn’t. Prefer passing messages over sharing; when threads must share changing data, put it in a Mutex (an atomic for a single number), and wrap it in Arc only when the threads aren’t scoped. In async code the choices change; Async, futures & Tokio covers that.

    Under the hood

    thread::spawn asks the operating system for a new thread with its own stack (2 MiB by default today; thread::Builder lets you choose). Rust adds no runtime of its own: no scheduler, no thread pool, no garbage collector to coordinate with. A Node worker is heavier: each one starts its own V8 instance with its own heap and event loop, which is why it can’t see your objects.A Thread is the same kind of OS thread; Task.Run borrows one from the .NET thread pool instead of creating it.

    An Arc<Mutex<i32>> is one heap allocation holding the reference counts, the lock and the data, side by side. Two handles to it look like this:

    use std::sync::{Arc, Mutex};
    
    let hits = Arc::new(Mutex::new(0));
    let worker_hits = Arc::clone(&hits);
    *worker_hits.lock().unwrap() += 1;
    let owners = Arc::strong_count(&hits);
    println!("owners: {owners}, hits: {}", hits.lock().unwrap());

    Output

    owners: 2, hits: 1
    Two Arc handles to one MutexOn the stack, hits and worker_hits are each a single pointer to the same heap block. In a real program they would live on different threads' stacks. The heap block holds the strong count (2), the weak count, the Mutex's lock state, its poison flag and the value 1. The value can only be reached through the lock.StackHeaphits: Arc<Mutex<i32>>ptrworker_hits: Arc<Mutex<i32>>ptrone allocation: Arc counts, then the Mutexstrong 2weaklockpoison1
    Two Arc handles to one Mutex. On the stack, hits and worker_hits are each a single pointer to the same heap block. In a real program they would live on different threads' stacks. The heap block holds the strong count (2), the weak count, the Mutex's lock state, its poison flag and the value 1. The value can only be reached through the lock.

    Cloning an Arc copies one pointer and atomically adds one to the strong count; dropping one subtracts one, and the last drop frees the block. The lock is a few bytes of state that the standard library manages with the operating system’s own primitives (a futex on Linux, for example), so an uncontended lock() is a single atomic operation, with no system call. The value sits right after it, and MutexGuard is the only safe way to get a reference to it.

    That’s the design choice that makes data races impossible: in C#, a lock and the data it protects are two separate things linked only by your discipline;in languages with shared memory, a lock and the data it protects are usually two separate things linked only by your discipline; in Rust, the data is inside the lock, and the type system won’t hand out a reference to it any other way.

    Common pitfalls

    Common pitfallThreads stop when main returns

    When main returns, a Rust program exits, and any spawned thread still running is stopped mid-work. Node is different: it keeps the process alive until every worker has finished.So Rust threads behave like C#‘s background threads (IsBackground = true). A Thread you create is a foreground thread by default and keeps the process alive; thread-pool work from Task.Run runs on background threads and doesn’t. Keep the JoinHandle and call join() on it, or use thread::scope, which can’t forget.

    Common pitfallA receive loop that never ends

    for message in rx stops only when every Sender is gone. If main keeps its original tx after cloning it for the threads, the loop waits forever, and the program hangs with no error. Drop the original with drop(tx) after the last clone, or move it into the last thread instead of cloning it.

    Common pitfallLocking twice on one thread

    C#‘s lock, on a Lock or any other object, lets the same thread enter again while it already holds it. Rust’s Mutex doesn’t: if a thread calls lock() while it still holds a guard from the same mutex, it deadlocks (or panics). The guard lives until the end of its scope, so a guard in a let holds the lock longer than you might think. Keep locked sections short: copy out what you need, and end the guard with a block or drop(guard) before calling anything that might lock again.

    use std::sync::Mutex;
    
    fn main() {
        let scores = Mutex::new(vec![3, 1, 2]);
        let best = {
            let guard = scores.lock().unwrap();
            guard.iter().max().copied()
        }; // the guard is dropped here, so the lock is free again
        scores.lock().unwrap().push(4);
        println!("{best:?} {}", scores.lock().unwrap().len());
    }

    Output

    Some(3) 4

    Try it yourself

    Exercise: port this to Rust

    Port this producer and consumer to Rust with a thread and a channel. The producer sends the squares of 1 to 5; the consumer prints each one as it arrives, then the total.

    Starting code in TypeScript
    squares.ts
    import { Worker, isMainThread, parentPort } from "node:worker_threads";
    
    type Message = { square: number } | { done: true };
    
    if (isMainThread) {
      const worker = new Worker(new URL(import.meta.url));
      let total = 0;
      worker.on("message", (message: Message) => {
        if ("square" in message) {
          console.log(`got ${message.square}`);
          total += message.square;
        } else {
          console.log(`total: ${total}`);
        }
      });
    } else {
      for (let n = 1; n <= 5; n++) {
        parentPort?.postMessage({ square: n * n } satisfies Message);
      }
      parentPort?.postMessage({ done: true } satisfies Message);
    }
    Starting code in C#
    Squares.cs
    using System.Threading.Channels;
    
    var channel = Channel.CreateUnbounded<int>();
    var producer = Task.Run(() =>
    {
        for (var n = 1; n <= 5; n++)
        {
            channel.Writer.TryWrite(n * n);
        }
        channel.Writer.Complete();
    });
    
    var total = 0;
    await foreach (var square in channel.Reader.ReadAllAsync())
    {
        Console.WriteLine($"got {square}");
        total += square;
    }
    await producer;
    Console.WriteLine($"total: {total}");

    Expected output

    got 1
    got 4
    got 9
    got 16
    got 25
    total: 55
    Show a hint

    Create the channel with mpsc::channel(), move the sender into a thread::spawn closure that sends n * n for n in 1..=5, then loop over the receiver in main. The loop ends when the thread finishes, because its sender is dropped.

    Show a solution
    use std::sync::mpsc;
    use std::thread;
    
    fn main() {
        let (tx, rx) = mpsc::channel();
        let producer = thread::spawn(move || {
            for n in 1..=5 {
                tx.send(n * n).unwrap();
            }
        });
    
        let mut total = 0;
        for square in rx {
            println!("got {square}");
            total += square;
        }
        producer.join().unwrap();
        println!("total: {total}");
    }

    The producer thread owns tx, so when its closure returns, tx is dropped and the channel closes. That ends the for loop over rx, the same job Complete() or a final message does elsewhere. A single sender sends in order, so the output is always the same. Joining the producer afterwards passes on any panic from it.

    Saved in this browser only.