-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathmain.rs
More file actions
51 lines (45 loc) · 1.51 KB
/
Copy pathmain.rs
File metadata and controls
51 lines (45 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
extern crate dispatch;
use dispatch::{Queue, QueuePriority};
use std::io;
use std::process::exit;
/// 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.
fn prompt(mut sum: i32, queue: Queue) {
queue.clone().exec_async(move || {
let main = Queue::main();
// Print our prompt on the main thread and wait until it's complete
main.exec_sync(|| {
println!("Enter a number:");
});
// Read the number the user enters
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
if let Ok(num) = input.trim().parse::<i32>() {
sum += num;
// Print the sum on the main thread and wait until it's complete
main.exec_sync(|| {
println!("Sum is {}\n", sum);
});
// Do it again!
prompt(sum, queue);
} else {
// Bail if no number was entered
main.exec_async(|| {
println!("Not a number, exiting.");
exit(0);
});
}
});
}
fn main() {
// Read from stdin on a background queue so that the main queue is free
// to handle other events. All printing still occurs through the main
// queue to avoid jumbled output.
prompt(0, Queue::global(QueuePriority::Default));
unsafe {
dispatch::ffi::dispatch_main();
}
}