|
| 1 | +// Tim has to complete a few chores today, before he's allowed to play soccer |
| 2 | +// with his friends. His friends decide to help him. Working together, they |
| 3 | +// finish the chores earlier and have more time left to play soccer. |
| 4 | +// |
| 5 | +// Let's simulate this using asynchronous programming. Each boy is represented |
| 6 | +// as an asynchronous task, which can be executed concurrently (they can be |
| 7 | +// working at the same time). |
| 8 | + |
| 9 | +use std::sync::atomic::{AtomicU8, Ordering}; |
| 10 | + |
| 11 | +fn do_chores() { |
| 12 | + // Async tasks need to be executed by a "runtime", which is not provided by |
| 13 | + // Rust's standard library. We use the popular "tokio" runtime here. |
| 14 | + let rt = tokio::runtime::Builder::new_current_thread() |
| 15 | + .build() |
| 16 | + .unwrap(); |
| 17 | + |
| 18 | + let task_tim = rt.spawn(tim()); |
| 19 | + let task_carl = rt.spawn(carl()); |
| 20 | + let task_nick = rt.spawn(nick()); |
| 21 | + |
| 22 | + // Block the runtime on a task that waits for all boys to finish the chores. |
| 23 | + // TODO: "await" all three tasks to fix the compiler errors. |
| 24 | + rt.block_on(async { |
| 25 | + task_tim.await.unwrap(); |
| 26 | + task_carl.await.unwrap(); |
| 27 | + task_nick.await.unwrap(); |
| 28 | + }); |
| 29 | + |
| 30 | + assert_eq!( |
| 31 | + CHORES_DONE.load(Ordering::SeqCst), |
| 32 | + 3, |
| 33 | + "Did you (a)wait for all the boys to finish the chores?" |
| 34 | + ); |
| 35 | + println!("Ready to play soccer!"); |
| 36 | +} |
| 37 | + |
| 38 | +/// Used by "mom" to check that all chores are done before Tim plays soccer :-) |
| 39 | +static CHORES_DONE: AtomicU8 = AtomicU8::new(0); |
| 40 | + |
| 41 | +async fn tim() { |
| 42 | + println!("Cleaning my room..."); |
| 43 | + CHORES_DONE.fetch_add(1, Ordering::SeqCst); |
| 44 | +} |
| 45 | + |
| 46 | +async fn carl() { |
| 47 | + println!("Washing the dishes..."); |
| 48 | + CHORES_DONE.fetch_add(1, Ordering::SeqCst); |
| 49 | +} |
| 50 | + |
| 51 | +async fn nick() { |
| 52 | + println!("Mowing the lawn..."); |
| 53 | + CHORES_DONE.fetch_add(1, Ordering::SeqCst); |
| 54 | +} |
| 55 | + |
| 56 | +fn main() { |
| 57 | + do_chores(); |
| 58 | +} |
0 commit comments