
Tokio & Async I/O
Tokio runtime, async tasks, select!, join!, timeout, tokio::spawn, async file/network I/O
1What is the main role of the Tokio runtime in an asynchronous Rust application?
What is the main role of the Tokio runtime in an asynchronous Rust application?
回答
The Tokio runtime provides an executor that polls futures until completion. It also manages a multi-threaded scheduler (by default) to distribute tasks across multiple OS threads, and a reactor for asynchronous I/O operations. Without a runtime, Rust futures do nothing as they are lazy by default.
2How to initialize the Tokio runtime with the #[tokio::main] macro?
How to initialize the Tokio runtime with the #[tokio::main] macro?
回答
The #[tokio::main] macro transforms an async main() function into a synchronous entry point that creates a multi-threaded Tokio runtime and executes the async function. This macro automatically generates the boilerplate needed to create the runtime and block until the main future completes.
3What is the difference between #[tokio::main] and #[tokio::main(flavor = "current_thread")]?
What is the difference between #[tokio::main] and #[tokio::main(flavor = "current_thread")]?
回答
By default, #[tokio::main] creates a multi-threaded runtime that distributes tasks across a pool of worker threads. With flavor = "current_thread", the runtime executes all tasks on the main thread only, which is useful for tests, simple applications, or when sharing data between threads should be avoided.
What does tokio::spawn() do and what type does it return?
Why must futures passed to tokio::spawn() be 'static?
+19 面接問題