SHARE
TWEET

Untitled

a guest Jun 18th, 2019 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use crossbeam_channel::{Receiver, Sender};
  2. use futures::Future;
  3. use std::{
  4.     pin::Pin,
  5.     sync::{
  6.         atomic::{AtomicBool, Ordering},
  7.         Arc,
  8.     },
  9.     task::{Context, Poll, Waker},
  10. };
  11.  
  12. pub fn new_pair() -> (Publisher, Subscriber) {
  13.     let finished = Arc::new(AtomicBool::new(false));
  14.     let (sender, receiver) = crossbeam_channel::unbounded();
  15.  
  16.     (
  17.         Publisher {
  18.             finished: finished.clone(),
  19.             receiver,
  20.         },
  21.         Subscriber { finished, sender },
  22.     )
  23. }
  24.  
  25. #[derive(Clone)]
  26. pub struct Publisher {
  27.     finished: Arc<AtomicBool>,
  28.     receiver: Receiver<Waker>,
  29. }
  30.  
  31. impl Publisher {
  32.     fn finish(self) {
  33.         self.finished.store(true, Ordering::SeqCst);
  34.         while let Ok(waker) = self.receiver.try_recv() {
  35.             waker.wake()
  36.         }
  37.     }
  38. }
  39.  
  40. pub struct Subscriber {
  41.     finished: Arc<AtomicBool>,
  42.     sender: Sender<Waker>,
  43. }
  44.  
  45. impl Future for Subscriber {
  46.     type Output = ();
  47.  
  48.     fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
  49.         let _ = self.sender.send(cx.waker().clone());
  50.  
  51.         if self.finished.load(Ordering::SeqCst) {
  52.             Poll::Ready(())
  53.         } else {
  54.             Poll::Pending
  55.         }
  56.     }
  57. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top