Skip to content

Commit c4958b6

Browse files
committed
Simplify pin example slightly
This reduces the vertical space needed by the example, thus making it easier to keep on the screen while refactoring it.
1 parent 3175751 commit c4958b6

File tree

1 file changed

+9
-17
lines changed
  • src/concurrency/async-pitfalls

1 file changed

+9
-17
lines changed
Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,40 @@
1+
use anyhow::Result;
12
use tokio::sync::{mpsc, oneshot};
2-
use tokio::task::spawn;
33
use tokio::time::{sleep, Duration};
44

5-
// A work item. In this case, just sleep for the given time and respond
6-
// with a message on the `respond_on` channel.
75
#[derive(Debug)]
86
struct Work {
97
input: u32,
108
respond_on: oneshot::Sender<u32>,
119
}
1210

13-
// A worker which listens for work on a queue and performs it.
1411
async fn worker(mut work_queue: mpsc::Receiver<Work>) {
1512
let mut _iterations = 0;
1613
loop {
1714
tokio::select! {
1815
Some(work) = work_queue.recv() => {
1916
sleep(Duration::from_millis(10)).await; // Pretend to work.
20-
work.respond_on
21-
.send(work.input * 1000)
22-
.expect("failed to send response");
17+
work.respond_on.send(work.input * 1000).unwrap();
2318
_iterations += 1;
2419
}
2520
// TODO: report number of iterations every 100ms
2621
}
2722
}
2823
}
2924

30-
// A requester which requests work and waits for it to complete.
31-
async fn do_work(work_queue: &mpsc::Sender<Work>, input: u32) -> u32 {
25+
async fn do_work(work_queue: &mpsc::Sender<Work>, input: u32) -> Result<u32> {
3226
let (tx, rx) = oneshot::channel();
33-
work_queue
34-
.send(Work { input, respond_on: tx })
35-
.await
36-
.expect("failed to send on work queue");
37-
rx.await.expect("failed waiting for response")
27+
work_queue.send(Work { input, respond_on: tx }).await?;
28+
Ok(rx.await?)
3829
}
3930

4031
#[tokio::main]
41-
async fn main() {
32+
async fn main() -> Result<()> {
4233
let (tx, rx) = mpsc::channel(10);
43-
spawn(worker(rx));
34+
tokio::spawn(worker(rx));
4435
for i in 0..100 {
45-
let resp = do_work(&tx, i).await;
36+
let resp = do_work(&tx, i).await?;
4637
println!("work result for iteration {i}: {resp}");
4738
}
39+
Ok(())
4840
}

0 commit comments

Comments
 (0)