A Visual Journey Through Async Rust

https://news.ycombinator.com/rss Hits: 10
Summary

A Visual Journey Through Async Rust I'm a visual and experimental learner. To truly understand something, I need to tinker with it and see it run with my own eyes. To truly understand async execution, I want to visualize it. What order are things happening in? Do concurrent futures affect each other? How do tasks and threads relate? Plotting network calls or file system operations is boring. Let's draw something. All visualization code is available here To visualize the passing of time, we'll plot out some shape. A simple sine wave will do nicely. First, we create a future that asynchronously computes N values of the sine function. In each iteration, we compute a value and yield_now().await to yield execution to other futures. We send these computed values to a channel and later use matplotlib and pyo3 to graphically display the results. /// Each calculated sine value is a sample we keep track of struct Sample { fut_name: String, value: f32, t: u128 } async fn produce_sin(run_start: Instant, fut_name: String, tx: mpsc::UnboundedSender<Sample>) { for i in 1..N { let t = run_start.elapsed().as_micros(); let value = sin(i); tx.send(Sample { fut_name, value, t }).unwrap(); // yield execution so that other futures can do their thing tokio::task::yield_now().await; } } Now, let's create a couple of these and see our two sine waves calculated side by side: #[tokio::main] async fn main() { let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); let mut futs = Vec::new(); let run_start = Instant::now(); futs.push(produce_sin(run_start, "fut1", tx.clone()).boxed()); futs.push(produce_sin(run_start, "fut2", tx.clone()).boxed()); futures::future::join_all(futs).await; drop(tx); plot_samples(rx).await; } This is what we get: Alright! We managed to plot two sine waves in the most convoluted method ever! And both graphs are plotted parallel to one another. Could it be that Tokio futures are actually parallel and not just concurrent? Let's take a closer look. First, let's add the si...

First seen: 2025-04-25 08:54

Last seen: 2025-04-25 17:56