A Rust Async Primer-Pt 3

Clay Ratliff
8 min readJul 12, 2022

Part 2 of this series used a trivial example to explain the basic principles and components of asynchronous Rust. In this one, we’ll demonstrate how to include a separate runtime crate and use it to run concurrent tasks, as well as give a brief comparison of the current options.

Photo by Markus Spiske on Unsplash

When we last left off we were using the primitive executor that is available with the futures crate, sometimes called futures-rs. The futures crate provides the common abstraction layer for async behavior in the Rust language. It is intended to be the basis for creating complex runtimes. As discussed in the previous articles, this is by design. Unless you intend to create a custom runtime, executors, etc., from scratch, you probably won’t be using futures directly.

I’ve chosen to use the async-std crate for this example simply because it’s easily read by anyone already familiar with the Rust std library. I’ll also be using timers to demonstrate that we’re actually running in a concurrent fashion as expected.

First, we’ll set up our cargo.toml file as follows.

[package]
name = "rust-async"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html[dependencies]
async-std = "1.12.0"
futures = "0.3"
rand = "0.8.5"

I simply reused the original cargo.toml file and added the async-std and the rand crates as dependencies. We add the rand crate so that we can generate random sleep times for our function.

Next, we’ll alter the main.rs file to look like this:

use std::time::{Instant, Duration};
use async_std::task;
use rand::Rng;
fn main() {
let start_time = Instant::now();
task::block_on(async_main());
print!("Completed in {} ms", start_time.elapsed().as_millis());
}async fn async_main() {
let long_running_stuff = make_coffee_and_bacon();
let other_stuff = make_eggs();
futures::join!(long_running_stuff, other_stuff);
}
async fn make_coffee_and_bacon() {
futures::join!(make_coffee(), make_bacon());
}
async fn make_coffee() {…
Clay Ratliff

Looking for our dreams in the second half of our lives as a novice sailors as we learn to live on our floating home SV Fearless https://svfearless.substack.com/