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