|
1 | 1 | use csplib::*;
|
2 | 2 |
|
| 3 | +#[csplib::process] |
| 4 | +struct Ping { |
| 5 | + #[input] |
| 6 | + x: String, |
| 7 | + #[output] |
| 8 | + y: String, |
| 9 | +} |
| 10 | +async fn run_ping(inner: PingInner) -> Result<String> { |
| 11 | + let s = "ping".to_owned(); |
| 12 | + inner.y.put(s)?; |
| 13 | + tokio::task::yield_now().await; |
| 14 | + let y = inner.x.reader().get().await?; |
| 15 | + Ok(y) |
| 16 | +} |
| 17 | +#[csplib::process] |
| 18 | +struct Pong { |
| 19 | + #[input] |
| 20 | + x: String, |
| 21 | + #[output] |
| 22 | + y: String, |
| 23 | +} |
| 24 | +async fn run_pong(inner: PongInner) -> Result<()> { |
| 25 | + let x = inner.x.reader().get().await?; |
| 26 | + tokio::task::yield_now().await; |
| 27 | + let s = format!("{}-pong", x); |
| 28 | + inner.y.put(s).unwrap(); |
| 29 | + Ok(()) |
| 30 | +} |
| 31 | + |
3 | 32 | #[tokio::test]
|
4 | 33 | async fn pingpong() {
|
5 |
| - let (w1, ch1) = channel(); |
6 |
| - let (w2, ch2) = channel(); |
7 |
| - tokio::spawn({ |
8 |
| - let r1 = ch1.reader(); |
9 |
| - async move { |
10 |
| - let x = r1.get().await.unwrap(); |
11 |
| - tokio::task::yield_now().await; |
12 |
| - let s = format!("{}pong", x); |
13 |
| - w2.put(s).unwrap(); |
14 |
| - } |
15 |
| - }); |
16 |
| - let y = tokio::spawn({ |
17 |
| - let r2 = ch2.reader(); |
18 |
| - async move { |
19 |
| - let x = "ping".to_owned(); |
20 |
| - w1.put(x).unwrap(); |
21 |
| - tokio::task::yield_now().await; |
22 |
| - let y = r2.get().await.unwrap(); |
23 |
| - y |
24 |
| - } |
25 |
| - }) |
26 |
| - .await |
27 |
| - .unwrap(); |
28 |
| - assert_eq!(y, "pingpong") |
| 34 | + let (ping, ping_inner) = Ping::new(); |
| 35 | + let (pong, pong_inner) = Pong::new(); |
| 36 | + |
| 37 | + tokio::spawn(connect(ping.y.reader(), pong.x)); |
| 38 | + tokio::spawn(connect(pong.y.reader(), ping.x)); |
| 39 | + |
| 40 | + tokio::spawn(run_pong(pong_inner)); |
| 41 | + tokio::time::sleep(std::time::Duration::from_secs(1)).await; |
| 42 | + |
| 43 | + let y = tokio::spawn(run_ping(ping_inner)).await.unwrap().unwrap(); |
| 44 | + assert_eq!(y, "ping-pong") |
29 | 45 | }
|
0 commit comments