typestar

Concurrency & async

15 steps in 5 sets of Rust.

Rust's claim about concurrency is stronger than its claim about memory: data races are a compile error, not a debugging session. Threads first, then shared state with Arc and Mutex, then channels.

The last set is async with tokio, which is a different model again and worth keeping separate in your head. Fifteen steps, and the compiler is doing more for you here than anywhere else in the language.

Start this tour

Threads

  • Spawning threadsspawn starts a thread and hands back a handle; join waits and collects its value.
  • move closuresA thread outlives the caller's stack frame, so it must own what it captures.
  • Scoped threadsthread::scope lets threads borrow local data, because they cannot outlive the scope.

Shared state

  • Arc and MutexArc shares ownership across threads; Mutex makes the mutation safe.
  • RwLockMany readers or one writer: the right lock when reads dominate.
  • AtomicsFor a counter or a flag, an atomic is cheaper than a mutex.

Channels

  • Channelsmpsc moves values between threads: many senders, one receiver.
  • A worker poolJobs down one channel, results back up another — a pool in twenty lines.

Async with tokio

Encore

  • parallel_sum.rsSplitting a big sum across threads, then comparing against the serial answer.

The other Rust tours