Skip to content

Commit

Permalink
fix: split the two tokio channel examples into separate modules
Browse files Browse the repository at this point in the history
  • Loading branch information
john-cd committed Dec 18, 2023
1 parent 7b27578 commit c322832
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 39 deletions.
43 changes: 4 additions & 39 deletions xmpl/tokio_example/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,43 +1,8 @@
use tokio::sync::mpsc;
use tokio::sync::oneshot;

async fn some_computation(input: u32) -> String {
format!("the result of computation {}", input)
}

async fn one_shot() {
let (tx, rx) = oneshot::channel();

tokio::spawn(async move {
let res = some_computation(0).await;
tx.send(res).unwrap();
// alernatively, return the value via the joinhandle returned by `spawn`
});

// Do other work while the computation is happening in the background

// Wait for the computation result
let res = rx.await.unwrap();
println!("{}", res);
}

async fn multi_producer_single_receiver() {
let (tx, mut rx) = mpsc::channel(100);

tokio::spawn(async move {
for i in 1..=10 {
let res = some_computation(i).await;
tx.send(res).await.unwrap();
}
});

while let Some(res) = rx.recv().await {
println!("{}", res);
}
}
mod mpsc;
mod oneshot;

#[tokio::main]
async fn main() {
one_shot().await;
multi_producer_single_receiver().await;
oneshot::one_shot().await;
mpsc::multi_producer_single_receiver().await;
}
20 changes: 20 additions & 0 deletions xmpl/tokio_example/src/mpsc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use tokio::sync::mpsc;

async fn some_computation(input: u32) -> String {
format!("the result of computation {}", input)
}

pub async fn multi_producer_single_receiver() {
let (tx, mut rx) = mpsc::channel(100);

tokio::spawn(async move {
for i in 1..=10 {
let res = some_computation(i).await;
tx.send(res).await.unwrap();
}
});

while let Some(res) = rx.recv().await {
println!("{}", res);
}
}
21 changes: 21 additions & 0 deletions xmpl/tokio_example/src/oneshot.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use tokio::sync::oneshot;

async fn some_computation(input: u32) -> String {
format!("the result of computation {}", input)
}

pub async fn one_shot() {
let (tx, rx) = oneshot::channel();

tokio::spawn(async move {
let res = some_computation(0).await;
tx.send(res).unwrap();
// alernatively, return the value via the joinhandle returned by `spawn`
});

// Do other work while the computation is happening in the background

// Wait for the computation result
let res = rx.await.unwrap();
println!("{}", res);
}

0 comments on commit c322832

Please sign in to comment.