22.3 Threads vs. Async
Rust offers two primary ways to execute tasks that may overlap in time:
- Threads: Each Rust thread maps to a native OS thread, scheduled by the operating system with preemptive multitasking.
- Async: Utilizes cooperative scheduling, where tasks explicitly yield (e.g., at
await
points) to let other tasks run. This is particularly effective for I/O-bound workloads, as tasks often wait for external events and can yield control during these wait periods.
Choosing between threads and async typically depends on the workload:
- Threads: Simplify many CPU-bound or long-running tasks that largely run independently.
- Async: More efficient for I/O-bound workloads that spend significant time waiting (e.g., network or disk operations). You can manage many tasks with relatively few OS threads, reducing context-switch overhead.
Note: Rust's async ecosystem can be intricate, and async tasks must yield periodically to avoid blocking other tasks running on the same thread.