I've learned everything I wanted to from the book, time to start on rush

This commit is contained in:
Rowan Torbitzky-Lane 2025-04-02 16:25:26 -05:00
parent 0fd24e1c3a
commit b94ab30230

View File

@ -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}");
// });
});
}