Learning paths / Rust: threads to async

Rust: threads to async

move and Arc<Mutex>, channels, then how Tokio tasks yield, block, and race with select!.

Start: step 1

6 steps · a step counts once you play it to the end

  1. closure may outlive the current function, explainedRust · Basicsthread::spawn needs a closure that owns what it uses. move hands names to the new thread, main waits in join(), and names is dropped on the thread.
  2. Sharing a counter between threads with Arc<Mutex<T>>Rust · BasicsTwo threads add 1 to a shared counter. The second waits in lock() until the first drops its guard.
  3. mpsc channels: send, recv, and when the loop endsRust · Basicssend never waits for main: the value goes into the channel. main waits in recv(), and its for loop ends once the producer drops tx.
  4. Tokio tasks switch only at .awaitRust · IntermediateTwo tasks share one thread. They take turns, and every switch happens at an .await.
  5. Blocking in async code stalls every taskRust · Intermediatemain calls a blocking sleep on the runtime's only thread. The ticker can't tick until it ends.
  6. tokio::select!: the first branch wins, the others are droppedRust · Intermediateselect! races fetch against a 50 ms timer on main's task. The timer wins, so fetch is dropped mid-await and fetch ends never prints.

All learning paths · All scenarios