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!.
- 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.
- 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.
- 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.
- Tokio tasks switch only at .awaitRust · IntermediateTwo tasks share one thread. They take turns, and every switch happens at an .await.
- 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.
- 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.