Skip to content

Instantly share code, notes, and snippets.

@matthauck
Created November 6, 2017 07:13
Show Gist options
  • Save matthauck/0cd5b87383a508e922fa69d53bfea5c5 to your computer and use it in GitHub Desktop.
Save matthauck/0cd5b87383a508e922fa69d53bfea5c5 to your computer and use it in GitHub Desktop.

Revisions

  1. matthauck created this gist Nov 6, 2017.
    47 changes: 47 additions & 0 deletions async_poller.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    use std::sync::Arc;
    use std::sync::mpsc::{SyncSender, sync_channel};
    use std::thread;

    use futures::{self, Async, Future};
    use futures::executor::{Notify, Spawn};

    pub type VoidFuture = Box<Future<Item = (), Error = ()>>;

    pub fn consume(mut fut: VoidFuture) {
    let (tx, rx) = sync_channel(1);
    let mut spawned = futures::executor::spawn(fut);
    let notifier = Arc::new(AsyncNotifier { sender: Arc::new(tx) });

    loop {
    match spawned.poll_future_notify(&notifier, 0) {
    Ok(Async::Ready(_)) => {
    debug!("Async future finished");
    break;
    }
    Ok(Async::NotReady) => {
    debug!("Async future not ready");
    if let Err(_) = rx.recv() {
    error!("Error waiting for future. Aborting");
    break;
    }
    debug!("Async future woke up");
    }
    Err(_) => {
    error!("Error polling async future.");
    break;
    }
    }
    }
    }

    #[derive(Clone)]
    struct AsyncNotifier {
    sender: Arc<SyncSender<()>>,
    }

    impl Notify for AsyncNotifier {
    fn notify(&self, id: usize) {
    debug!("AsyncNotifier received notification");
    let _ = self.sender.send(());
    }
    }