From b94ab302303f99a0a0db9a385d0cba4615c2e354 Mon Sep 17 00:00:00 2001 From: Rowan Torbitzky-Lane Date: Wed, 2 Apr 2025 16:25:26 -0500 Subject: [PATCH] I've learned everything I wanted to from the book, time to start on rush --- ch17/concurrency-with-async/src/main.rs | 78 ++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/ch17/concurrency-with-async/src/main.rs b/ch17/concurrency-with-async/src/main.rs index 07ef731..2af9db1 100644 --- a/ch17/concurrency-with-async/src/main.rs +++ b/ch17/concurrency-with-async/src/main.rs @@ -2,8 +2,84 @@ //! //! Similar to working with threads. +extern crate trpl; + use std::time::Duration; fn main() { - println!("Hello, world!"); + // trpl::run(async { + // let handle = trpl::spawn_task(async { + // for i in 1..10 { + // println!("hi number {i} from the first task!"); + // trpl::sleep(Duration::from_millis(500)).await; + // } + // }); + + // for i in 1..5 { + // println!("hi number {i} from the second task!"); + // trpl::sleep(Duration::from_millis(500)).await; + // } + + // // Makes it so the program runs until both of these loops are + // // finished. + // handle.await.unwrap(); + // }); + + trpl::run(async { + let fut1 = async { + for i in 1..10 { + println!("hi number {i} from the first task!"); + trpl::sleep(Duration::from_millis(500)).await; + } + }; + + let fut2 = async { + for i in 1..5 { + println!("hi number {i} from the second task!"); + trpl::sleep(Duration::from_millis(500)).await; + } + }; + + // `trpl::join` function is fair meaning: checks each + // future equally often, alternating between them, never + // lets one race ahead if the other is ready. + trpl::join(fut1, fut2).await; + + // message passing + // + // Can also share data between futures like this. + + // async version of mutliple-producer, single consumer. + // trpl::run(async { + let (tx, mut rx) = trpl::channel(); + + let tx_fut = async { + let vals = vec![ + String::from("hi"), + String::from("from"), + String::from("the"), + String::from("future"), + ]; + + for val in vals { + tx.send(val).unwrap(); + trpl::sleep(Duration::from_millis(500)).await; + } + }; + + let rx_fut = async { + while let Some(value) = rx.recv().await { + println!("received '{value}'"); + } + }; + + trpl::join(tx_fut, rx_fut).await; + + // let val = String::from("hi"); + // tx.send(val).unwrap(); + + // let received = rx.recv().await.unwrap(); + // println!("Got: {received}"); + // }); + }); }