2019-07-03 09:37:33 -05:00
|
|
|
// run-pass
|
|
|
|
|
2019-02-05 22:32:35 -06:00
|
|
|
// aux-build:arc_wake.rs
|
|
|
|
|
|
|
|
extern crate arc_wake;
|
|
|
|
|
2018-05-30 20:23:10 -05:00
|
|
|
use std::future::Future;
|
2018-09-14 19:40:52 -05:00
|
|
|
use std::pin::Pin;
|
2018-05-30 20:23:10 -05:00
|
|
|
use std::sync::{
|
|
|
|
Arc,
|
|
|
|
atomic::{self, AtomicUsize},
|
|
|
|
};
|
|
|
|
use std::task::{
|
2019-03-11 18:56:00 -05:00
|
|
|
Context, Poll,
|
2018-05-30 20:23:10 -05:00
|
|
|
};
|
2019-02-05 22:32:35 -06:00
|
|
|
use arc_wake::ArcWake;
|
2019-02-03 14:59:51 -06:00
|
|
|
|
|
|
|
struct Counter {
|
|
|
|
wakes: AtomicUsize,
|
|
|
|
}
|
|
|
|
|
2019-02-03 16:59:22 -06:00
|
|
|
impl ArcWake for Counter {
|
2019-04-05 13:46:30 -05:00
|
|
|
fn wake(self: Arc<Self>) {
|
|
|
|
Self::wake_by_ref(&self)
|
|
|
|
}
|
|
|
|
fn wake_by_ref(arc_self: &Arc<Self>) {
|
2019-02-03 14:59:51 -06:00
|
|
|
arc_self.wakes.fetch_add(1, atomic::Ordering::SeqCst);
|
2018-05-30 20:23:10 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct MyFuture;
|
|
|
|
|
|
|
|
impl Future for MyFuture {
|
|
|
|
type Output = ();
|
2019-03-11 18:56:00 -05:00
|
|
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
2019-02-03 14:59:51 -06:00
|
|
|
// Wake twice
|
2019-03-11 18:56:00 -05:00
|
|
|
let waker = cx.waker();
|
2019-04-05 13:46:30 -05:00
|
|
|
waker.wake_by_ref();
|
|
|
|
waker.wake_by_ref();
|
2018-05-30 20:23:10 -05:00
|
|
|
Poll::Ready(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-03 14:59:51 -06:00
|
|
|
fn test_waker() {
|
2018-05-30 20:23:10 -05:00
|
|
|
let counter = Arc::new(Counter {
|
2019-02-03 14:59:51 -06:00
|
|
|
wakes: AtomicUsize::new(0),
|
2018-05-30 20:23:10 -05:00
|
|
|
});
|
2019-02-03 14:59:51 -06:00
|
|
|
let waker = ArcWake::into_waker(counter.clone());
|
|
|
|
assert_eq!(2, Arc::strong_count(&counter));
|
2019-03-11 18:56:00 -05:00
|
|
|
{
|
|
|
|
let mut context = Context::from_waker(&waker);
|
|
|
|
assert_eq!(Poll::Ready(()), Pin::new(&mut MyFuture).poll(&mut context));
|
|
|
|
assert_eq!(2, counter.wakes.load(atomic::Ordering::SeqCst));
|
|
|
|
}
|
2019-02-03 14:59:51 -06:00
|
|
|
drop(waker);
|
|
|
|
assert_eq!(1, Arc::strong_count(&counter));
|
2018-05-30 20:23:10 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2019-02-03 14:59:51 -06:00
|
|
|
test_waker();
|
2018-05-30 20:23:10 -05:00
|
|
|
}
|