From the course: Rust: Asynchronous Programming with Tokio
Tokio's asynchronous runtime - Rust Tutorial
From the course: Rust: Asynchronous Programming with Tokio
Tokio's asynchronous runtime
- [Instructor] We know that asynchronous functions can call other asynchronous functions, but who calls the first asynchronous function? That magic happens in the Tokio main macro that is placed above your main function. The specifics of how this macro works is out of scope for this course, but from a high level, this macro starts an asynchronous runtime, it copies the function body of the main function, and then passes that body of code to the newly created asynchronous runtime. If you wanted to replicate this functionality, it would look something like this. By default, the Tokio main macro creates a multi-threaded runtime, which can schedule workers across multiple threads. To manually build that runtime, you call tokio::runtime::Builder::new_multi_thread. The .enable_all call is shorthand for enabling all of Tokio's features. Right now, there are only two features being enabled, IO and time, but this list will probably grow in the future. The .build call returns a result containing the new runtime. After we unwrap the runtime, we call the .block_on method. The .block_on method takes an asynchronous function, or block of code, and runs it to completion. If you look at the asynchronous code that was passed into the .block_on call, you'll notice that it's an exact copy of the code located in our main function of our Tokio Hello World program. Coming back to our original question, which was, who caused the first asynchronous function? The short answer is Tokio main macro. The long answer is no one calls it. What actually happens is that the code from the first asynchronous function, main, is copied and passed as an argument to a newly created asynchronous runtime's block on method. All right, now that we understand how Tokio's asynchronous runtime works, it's time to start looking at the features that make Tokio great.