We’ll create a version of the first example in Chapter 7 since it’s the simplest one to start with. Our only focus is showing how to schedule and drive the runtimes more efficiently.

We start with the following steps:

  1. Create a new project and name it a-runtime (alternatively, navigate to ch08/a-runtime in the book’s repository).
  2. Copy the future.rs and http.rs files in the src folder from the first project we created in Chapter 7, named a-coroutine (alternatively, copy the files from ch07/a-coroutine in the book’s repository) to the src folder in our new project.
  3. Make sure to add mio as a dependency by adding the following to Cargo.toml:

[dependencies]
mio = { version = “0.8”, features = [“net”, “os-poll”] }

  1. Create a new file in the src folder called runtime.rs.

We’ll use corofy to change the following coroutine/wait program into its state machine representation that we can run.

In src/main.rs, add the following code:

ch08/a-runtime/src/main.rs
mod future;
mod http;
mod runtime;
use future::{Future, PollState};
use runtime::Runtime;
fn main() {
    let future = async_main();
    let mut runtime = Runtime::new();
    runtime.block_on(future);
}
coroutine fn async_main() {
    println!(“Program starting”);
    let txt = http::Http::get(“/600/HelloAsyncAwait”).wait;
    println!(“{txt}”);
    let txt = http::Http::get(“/400/HelloAsyncAwait”).wait;
    println!(“{txt}”);
}

This program is basically the same one we created in Chapter 7, only this time, we create it from our coroutine/wait syntax instead of writing the state machine by hand. Next, we need to transform this into code by using corofy since the compiler doesn’t recognize our own coroutine/wait syntax.

  1. If you’re in the root folder of a-runtime, run corofy ./src/main.rs.
  2. You should now have a file that’s called main_corofied.rs.
  3. Delete the code in main.rs and copy the contents of main_corofied.rs into main.rs.
  4. You can now delete main_corofied.rs since we won’t need it going forward.

If everything is done right, the project structure should now look like this:
src
 |– future.rs
 |– http.rs
 |– main.rs
 |– runtime.rs

Tip

You can always refer to the book’s repository to make sure everything is correct. The correct example is located in the ch08/a-runtime folder. In the repository, you’ll also find a file called main_orig.rs in the root folder that contains the coroutine/wait program if you want to rerun it or have problems getting everything working correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *