Skip to main content

sleep/
sleep.rs

1extern crate liblightning;
2
3use std::thread;
4use std::time::Duration;
5use std::sync::mpsc;
6use std::rc::Rc;
7use std::cell::Cell;
8use liblightning::Scheduler;
9use liblightning::Promise;
10use liblightning::Yieldable;
11
12fn sleep_ms(c: &mut Yieldable, ms: u64) {
13    let p = Promise::new(move |h| {
14        let h = h.into_sendable();
15        thread::spawn(move || {
16            thread::sleep(Duration::from_millis(ms));
17            h.notify();
18        });
19    });
20    c.yield_now(&p);
21}
22
23fn main() {
24    let mut sched = Scheduler::new_default();
25    let state = sched.get_state();
26    let state2 = state.clone();
27
28    sched.run_value_promise_to_end(state.prepare_coroutine(move |c| {
29        let done_count: Rc<Cell<usize>> = Rc::new(Cell::new(0));
30        let done_count_2 = done_count.clone();
31
32        let p = Promise::new(move |handle| {
33            // TODO: Implement Promise::all
34
35            let handle = Rc::new(Cell::new(Some(handle)));
36            let handle2 = handle.clone();
37
38            state2.start_coroutine(move |c| {
39                println!("Begin 1");
40                sleep_ms(c, 500);
41                println!("End 1");
42                done_count.set(done_count.get() + 1);
43                if done_count.get() == 2 {
44                    handle.replace(None).unwrap().notify();
45                }
46            });
47
48            state2.start_coroutine(move |c| {
49                println!("Begin 2");
50                sleep_ms(c, 500);
51                println!("End 2");
52                done_count_2.set(done_count_2.get() + 1);
53                if done_count_2.get() == 2 {
54                    handle2.replace(None).unwrap().notify();
55                }
56            });
57        });
58
59        c.yield_now(&p);
60    })).unwrap();
61}