A look back at asynchronous Rust

General introduction

Future cancelling problem

async fn read_send(file: &mut File, channel: &mut Sender<...>) {
loop {
let data = read_next(file).await;
let items = parse(&data);
for item in items {
channel.send(item).await;
}
}
}
let mut file = ...;
let mut channel = ...;
loop {
futures::select! {
_ => read_send(&mut file, &mut channel) => {},
some_data => socket.read_packet() => {
// ...
}
}
}
  • Rewrite the select! to not destroy the future. Example. This is arguably the best solution in that specific situation, but it can sometimes introduce a lot of complexity, for example if you want to re-create the future with a different File when the socket receives a message.
  • Ensure that read_send reads and sends atomically. Example. In my opinion the best overall solution, but this isn’t always possible or would introduce an overhead in complex situations.
  • Change the API of read_send and avoid any local variable across a yield point. Example. Real world example. This is also a good solution, but it can be hard to write such code, as it starts to become dangerously close to manually-written futures.
  • Don’t use select! and spawn a background task to do the reading. Use a channel to communicate with the background task if necessary, as pulling items from channels is cancellation-resilient. Example. Often the best solution, but adds latency and makes it impossible to access file and channel ever again.

The Send trait isn’t what it means anymore

fn background_task() {
let rc = std::rc::Rc::new(5);
let rc2 = rc.clone();
bar();
}
async fn background_task() {
let rc = std::rc::Rc::new(5);
let rc2 = rc.clone();
bar().await;
}

Flow control is hard

“Just spawn a new task”

Program introspection

Example graph showing how much CPU each task uses

tokio vs async-std vs no-std

Conclusion

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Leadership Techniques for the Software Architect

To make a difference

Git workflow — medium to large teams

Quality Control in China- Can You Do It Yourself?- Merchsprout.com

Engineering Notebook for Tufts Senior Capstone

Red Teaming for Pacific Rim CCDC 2017

Notes to Review in 20 sep 2018

This library uses your tests to auto-generate mocks

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
tomaka

tomaka

More from Medium

Data Structures in Typescript and Rust with Borsh

What is Rust and Why it is gaining Popularity?

Elixir — A Tincture for Functional Programming Part 1.5 Recursion

Ouroboros

The Technologies I’m Learning in 2022