main/main.rs
1extern crate dispatch;
2
3use std::io;
4use std::process::exit;
5use dispatch::{Queue, QueuePriority};
6
7/// Prompts for a number and adds it to the given sum.
8///
9/// Reading from stdin is done on the given queue.
10/// All printing is performed on the main queue.
11/// Repeats until the user stops entering numbers.
12fn 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
42fn main() {
43 // Read from stdin on a background queue so that the main queue is free
44 // to handle other events. All printing still occurs through the main
45 // queue to avoid jumbled output.
46 prompt(0, Queue::global(QueuePriority::Default));
47
48 unsafe {
49 dispatch::ffi::dispatch_main();
50 }
51}