azure_core/sleep/
thread.rs

1use futures::Future;
2use std::pin::Pin;
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::Arc;
5use std::task::{Context, Poll};
6use std::thread;
7use std::time::Duration;
8
9/// Creates a future that resolves after a specified duration of time.
10/// Uses a simple thread based implementation for sleep. A more efficient
11/// implementation is available by using the `tokio-sleep` crate feature.
12pub fn sleep(duration: Duration) -> Sleep {
13    Sleep {
14        signal: None,
15        duration,
16    }
17}
18
19#[derive(Debug)]
20pub struct Sleep {
21    signal: Option<Arc<AtomicBool>>,
22    duration: Duration,
23}
24
25impl Future for Sleep {
26    type Output = ();
27
28    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
29        if let Some(signal) = &self.signal {
30            if signal.load(Ordering::Acquire) {
31                Poll::Ready(())
32            } else {
33                Poll::Pending
34            }
35        } else {
36            let signal = Arc::new(AtomicBool::new(false));
37            let waker = cx.waker().clone();
38            let duration = self.duration;
39            self.get_mut().signal = Some(signal.clone());
40            thread::spawn(move || {
41                thread::sleep(duration);
42                signal.store(true, Ordering::Release);
43                waker.wake();
44            });
45            Poll::Pending
46        }
47    }
48}