From 519ce8dd85a394a9272a23238dbc4664a8af2143 Mon Sep 17 00:00:00 2001 From: Manuel Thalmann <m@nuth.ch> Date: Sun, 6 Apr 2025 21:57:17 +0200 Subject: [PATCH] Send messages from multiple tasks --- async-message-passing/src/main.rs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/async-message-passing/src/main.rs b/async-message-passing/src/main.rs index dbe3883..98a3ade 100644 --- a/async-message-passing/src/main.rs +++ b/async-message-passing/src/main.rs @@ -4,7 +4,8 @@ fn main() { trpl::run(async { let (tx, mut rx) = trpl::channel(); - let tx_fut = async move { + let tx1 = tx.clone(); + let tx1_fut = async move { let vals = vec![ String::from("hi"), String::from("from"), @@ -13,17 +14,31 @@ fn main() { ]; for val in vals { - tx.send(val).unwrap(); + tx1.send(val).unwrap(); trpl::sleep(Duration::from_millis(500)).await; } }; let rx_fut = async { while let Some(value) = rx.recv().await { - eprintln!("received '{value}'"); + println!("received '{value}'"); } }; - trpl::join(tx_fut, rx_fut).await; + let tx_fut = async move { + let vals = vec![ + String::from("more"), + String::from("messages"), + String::from("for"), + String::from("you"), + ]; + + for val in vals { + tx.send(val).unwrap(); + trpl::sleep(Duration::from_millis(1500)).await; + } + }; + + trpl::join3(tx1_fut, tx_fut, rx_fut).await; }); }