DEV Community

Explained: How does async work in Rust?

Bastian Gruber on April 02, 2019

This article will outline an overview of the why and how async exists in Rust. The differences between concurrency, parallelism and asynchronous c...
Collapse
 
rhymes profile image
rhymes • Edited

Hi Bastian! Nice overview of Rust's async support!

I think there's a bit of unintentional misleading in how you worded the following part:

The kernel already has the concept implemented (through threads and other concepts), however they are quite "expensive", which means there is just a finite amount of resources available and dealing with this problem on OS level adds a whole new level of complexity.

Kernels do have async IO implemented, so it's not "expensive" (I guess you're referring of the cost of threading here), you do talk about these kernel syscalls afterwards when you mention mio

Collapse
 
gruberb profile image
Bastian Gruber

Thank you for the feedback! I'll update the article accordingly in the near future!

Collapse
 
creepy_owlet profile image
Dmitry Tantsur

Hi Bastian,

I've learned the hard way that this is not quite right:

tokio::run(response_is_ok);

Depending on what happens inside client, this can hang forever. This actually does happen with reqwest::async since Hyper tend to spawn long-living futures, presumably for keep-alive connections in its pool.

What I had to use to make it reliable is

let mut rt = Runtime::new().expect("Cannot create a runtime");
rt.block_on(response_is_ok).expect("Failed");

As a nice side effect you get the outcome of the future as a Result, you don't have to force it to be Future<Item = (), Error = ()>.

Collapse
 
gruberb profile image
Bastian Gruber

Thats super helpful, thank you so much Dmitry!

Collapse
 
michall profile image
Michal Podhradsky

Thanks for a nice article - just one note when you talk about async concept On a software level, this was achieved through multi-threading -> in Node.js it is handled by Event loop on single thread rather than multi-threading.. Anyway it is great that tokio is going the same path Node.js went - definitely looking forward for using Rust on scalable server stuff in the future

Collapse
 
0xpr03 profile image
Aron Heinecke

As said on gitter: I wish I'd have these nice drawings when I started using tokio & futures :)

Collapse
 
nickytonline profile image
Nick Taylor • Edited

Been enjoying your posts about rust Bastian. 👏 I haven't dug too much into it yet, but hopefully will at some point this year.

Collapse
 
gruberb profile image
Bastian Gruber

Thanks for the feedback Nick! Always happy when I hit the right tone and depth, and the work reaches the people who are interested in it.