async_notify/
lib.rs

1//! A general version async Notify, like `tokio` Notify but can work with any async runtime.
2
3use std::future::Future;
4use std::ops::Deref;
5use std::pin::Pin;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::task::{Context, Poll, ready};
8
9use event_listener::{Event, EventListener, listener};
10use futures_core::Stream;
11use pin_project_lite::pin_project;
12
13/// Notify a single task to wake up.
14///
15/// `Notify` provides a basic mechanism to notify a single task of an event.
16/// `Notify` itself does not carry any data. Instead, it is to be used to signal
17/// another task to perform an operation.
18///
19/// If [`notify()`] is called **before** [`notified().await`], then the next call to
20/// [`notified().await`] will complete immediately, consuming the permit. Any
21/// subsequent calls to [`notified().await`] will wait for a new permit.
22///
23/// If [`notify()`] is called **multiple** times before [`notified().await`], only a
24/// **single** permit is stored. The next call to [`notified().await`] will
25/// complete immediately, but the one after will wait for a new permit.
26///
27/// [`notify()`]: Notify::notify
28/// [`notified().await`]: Notify::notified()
29///
30/// # Examples
31///
32/// Basic usage.
33///
34/// ```
35/// use std::sync::Arc;
36/// use async_notify::Notify;
37///
38/// async_global_executor::block_on(async {
39///    let notify = Arc::new(Notify::new());
40///    let notify2 = notify.clone();
41///
42///    async_global_executor::spawn(async move {
43///        notify2.notify();
44///        println!("sent notification");
45///    })
46///    .detach();
47///
48///    println!("received notification");
49///    notify.notified().await;
50/// })
51/// ```
52#[derive(Debug, Default)]
53pub struct Notify {
54    count: AtomicBool,
55    event: Event,
56}
57
58/// Like tokio Notify, this is a runtime independent Notify.
59impl Notify {
60    /// Create a [`Notify`]
61    pub const fn new() -> Self {
62        Self {
63            count: AtomicBool::new(false),
64            event: Event::new(),
65        }
66    }
67
68    /// Notifies a waiting task
69    ///
70    /// If a task is currently waiting, that task is notified. Otherwise, a
71    /// permit is stored in this `Notify` value and the **next** call to
72    /// [`notified().await`] will complete immediately consuming the permit made
73    /// available by this call to `notify()`.
74    ///
75    /// At most one permit may be stored by `Notify`. Many sequential calls to
76    /// `notify` will result in a single permit being stored. The next call to
77    /// `notified().await` will complete immediately, but the one after that
78    /// will wait.
79    ///
80    /// [`notified().await`]: Notify::notified()
81    ///
82    /// # Examples
83    ///
84    /// ```
85    /// use std::sync::Arc;
86    /// use async_notify::Notify;
87    ///
88    /// async_global_executor::block_on(async {
89    ///    let notify = Arc::new(Notify::new());
90    ///    let notify2 = notify.clone();
91    ///
92    ///    async_global_executor::spawn(async move {
93    ///        notify2.notify();
94    ///        println!("sent notification");
95    ///    })
96    ///    .detach();
97    ///
98    ///    println!("received notification");
99    ///    notify.notified().await;
100    /// })
101    /// ```
102    #[inline]
103    pub fn notify(&self) {
104        self.count.store(true, Ordering::Release);
105        self.event.notify(1);
106    }
107
108    /// Wait for a notification.
109    ///
110    /// Each `Notify` value holds a single permit. If a permit is available from
111    /// an earlier call to [`notify()`], then `notified().await` will complete
112    /// immediately, consuming that permit. Otherwise, `notified().await` waits
113    /// for a permit to be made available by the next call to `notify()`.
114    ///
115    /// This method is cancel safety.
116    ///
117    /// [`notify()`]: Notify::notify
118    #[inline]
119    pub async fn notified(&self) {
120        loop {
121            if self.fast_path() {
122                return;
123            }
124
125            listener!(self.event => listener);
126
127            if self.fast_path() {
128                return;
129            }
130
131            listener.await;
132        }
133    }
134
135    fn fast_path(&self) -> bool {
136        self.count
137            .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
138            .is_ok()
139    }
140}
141
142pin_project! {
143    /// A [`Stream`](Stream) [`Notify`] wrapper
144    pub struct NotifyStream<T: Deref<Target=Notify>> {
145        #[pin]
146        notify: T,
147        listener: Option<EventListener>,
148    }
149}
150
151impl<T: Deref<Target = Notify>> NotifyStream<T> {
152    /// Create [`NotifyStream`] from `T`
153    pub const fn new(notify: T) -> Self {
154        Self {
155            notify,
156            listener: None,
157        }
158    }
159
160    /// acquire the inner [`T`]
161    pub fn into_inner(self) -> T {
162        self.notify
163    }
164}
165
166impl<T: Deref<Target = Notify>> AsRef<Notify> for NotifyStream<T> {
167    fn as_ref(&self) -> &Notify {
168        self.notify.deref()
169    }
170}
171
172impl<T: Deref<Target = Notify>> Stream for NotifyStream<T> {
173    type Item = ();
174
175    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
176        let this = self.project();
177        let notify = this.notify.deref();
178
179        loop {
180            if notify.fast_path() {
181                *this.listener = None;
182
183                return Poll::Ready(Some(()));
184            }
185
186            match this.listener.as_mut() {
187                None => {
188                    let listener = notify.event.listen();
189                    *this.listener = Some(listener);
190                }
191                Some(listener) => {
192                    ready!(Pin::new(listener).poll(cx));
193                }
194            }
195        }
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use std::sync::Arc;
202
203    use futures_util::{FutureExt, StreamExt, select};
204
205    use super::*;
206
207    #[test]
208    fn test() {
209        async_global_executor::block_on(async {
210            let notify = Arc::new(Notify::new());
211            let notify2 = notify.clone();
212
213            async_global_executor::spawn(async move {
214                notify2.notify();
215                println!("sent notification");
216            })
217            .detach();
218
219            println!("received notification");
220            notify.notified().await;
221        })
222    }
223
224    #[test]
225    fn test_multi_notify() {
226        async_global_executor::block_on(async {
227            let notify = Arc::new(Notify::new());
228            let notify2 = notify.clone();
229
230            notify.notify();
231            notify.notify();
232
233            select! {
234                _ = notify2.notified().fuse() => {}
235                default => unreachable!("there should be notified")
236            }
237
238            select! {
239                _ = notify2.notified().fuse() => unreachable!("there should not be notified"),
240                default => {}
241            }
242
243            notify.notify();
244
245            select! {
246                _ = notify2.notified().fuse() => {}
247                default => unreachable!("there should be notified")
248            }
249        })
250    }
251
252    #[test]
253    fn stream() {
254        async_global_executor::block_on(async {
255            let notify = Arc::new(Notify::new());
256            let mut notify_stream = NotifyStream::new(notify.clone());
257
258            async_global_executor::spawn(async move {
259                notify.notify();
260                println!("sent notification");
261            })
262            .detach();
263
264            notify_stream.next().await.unwrap();
265        })
266    }
267}