Prompts for a number and adds it to the given sum. Reading from stdin is done on the given queue. All printing is performed on the main queue. Repeats until the user stops entering numbers.
(mut sum: i32, queue: Queue)
| 10 | /// All printing is performed on the main queue. |
| 11 | /// Repeats until the user stops entering numbers. |
| 12 | fn prompt(mut sum: i32, queue: Queue) { |
| 13 | queue.clone().exec_async(move || { |
| 14 | let main = Queue::main(); |
| 15 | // Print our prompt on the main thread and wait until it's complete |
| 16 | main.exec_sync(|| { |
| 17 | println!("Enter a number:"); |
| 18 | }); |
| 19 | |
| 20 | // Read the number the user enters |
| 21 | let mut input = String::new(); |
| 22 | io::stdin().read_line(&mut input).unwrap(); |
| 23 | |
| 24 | if let Ok(num) = input.trim().parse::<i32>() { |
| 25 | sum += num; |
| 26 | // Print the sum on the main thread and wait until it's complete |
| 27 | main.exec_sync(|| { |
| 28 | println!("Sum is {}\n", sum); |
| 29 | }); |
| 30 | // Do it again! |
| 31 | prompt(sum, queue); |
| 32 | } else { |
| 33 | // Bail if no number was entered |
| 34 | main.exec_async(|| { |
| 35 | println!("Not a number, exiting."); |
| 36 | exit(0); |
| 37 | }); |
| 38 | } |
| 39 | }); |
| 40 | } |
| 41 | |
| 42 | fn main() { |
| 43 | // Read from stdin on a background queue so that the main queue is free |
no test coverage detected