|
| 1 | +use anyhow::Result; |
1 | 2 | use tokio::sync::{mpsc, oneshot};
|
2 |
| -use tokio::task::spawn; |
3 | 3 | use tokio::time::{sleep, Duration};
|
4 | 4 |
|
5 |
| -// A work item. In this case, just sleep for the given time and respond |
6 |
| -// with a message on the `respond_on` channel. |
7 | 5 | #[derive(Debug)]
|
8 | 6 | struct Work {
|
9 | 7 | input: u32,
|
10 | 8 | respond_on: oneshot::Sender<u32>,
|
11 | 9 | }
|
12 | 10 |
|
13 |
| -// A worker which listens for work on a queue and performs it. |
14 | 11 | async fn worker(mut work_queue: mpsc::Receiver<Work>) {
|
15 | 12 | let mut _iterations = 0;
|
16 | 13 | loop {
|
17 | 14 | tokio::select! {
|
18 | 15 | Some(work) = work_queue.recv() => {
|
19 | 16 | 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(); |
23 | 18 | _iterations += 1;
|
24 | 19 | }
|
25 | 20 | // TODO: report number of iterations every 100ms
|
26 | 21 | }
|
27 | 22 | }
|
28 | 23 | }
|
29 | 24 |
|
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> { |
32 | 26 | 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?) |
38 | 29 | }
|
39 | 30 |
|
40 | 31 | #[tokio::main]
|
41 |
| -async fn main() { |
| 32 | +async fn main() -> Result<()> { |
42 | 33 | let (tx, rx) = mpsc::channel(10);
|
43 |
| - spawn(worker(rx)); |
| 34 | + tokio::spawn(worker(rx)); |
44 | 35 | for i in 0..100 {
|
45 |
| - let resp = do_work(&tx, i).await; |
| 36 | + let resp = do_work(&tx, i).await?; |
46 | 37 | println!("work result for iteration {i}: {resp}");
|
47 | 38 | }
|
| 39 | + Ok(()) |
48 | 40 | }
|
0 commit comments