extern crate gj;
use gj::Promise;
use gj::io::{AsyncRead, AsyncWrite, unix};
use std::time::Duration;
fn child_loop(delay: Duration,
stream: unix::Stream,
buf: Vec<u8>) -> Promise<(), gj::io::Error<(unix::Stream, Vec<u8>)>> {
::std::thread::sleep(delay);
stream.write(buf).then(move |(stream, buf)| {
child_loop(delay, stream, buf)
})
}
fn child(delay: Duration) -> Result<unix::Stream, Box<::std::error::Error>> {
let (_, stream) = try!(unix::spawn(move |parent_stream, wait_scope| {
try!(child_loop(delay, parent_stream, vec![0u8]).lift::<Box<::std::error::Error>>().wait(wait_scope));
Ok(())
}));
return Ok(stream);
}
fn listen_to_child(id: &'static str,
stream: unix::Stream,
buf: Vec<u8>) -> Promise<(), gj::io::Error<(unix::Stream, Vec<u8>)>> {
stream.read(buf, 1).then(move |(stream, buf, _n)| {
println!("heard back from {}", id);
listen_to_child(id, stream, buf)
})
}
fn parent_wait_loop() -> Promise<(), ::std::io::Error> {
println!("parent wait loop...");
gj::io::Timer.after_delay(Duration::from_millis(3000)).then(|()| {
parent_wait_loop()
})
}
pub fn main() {
gj::EventLoop::top_level(|wait_scope| {
let children = vec![
parent_wait_loop().lift::<Box<::std::error::Error>>(),
listen_to_child("CHILD 1", try!(child(Duration::from_millis(700))), vec![0]).lift(),
listen_to_child("CHILD 2", try!(child(Duration::from_millis(1900))), vec![0]).lift(),
listen_to_child("CHILD 3", try!(child(Duration::from_millis(2600))), vec![0]).lift()];
try!(Promise::all(children.into_iter()).wait(wait_scope));
Ok(())
}).unwrap();
}