use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
#[must_use = "yield_now returns a future that must be .awaited on."]
pub fn yield_now() -> YieldFuture {
YieldFuture { first_time: true }
}
#[derive(Debug)]
#[must_use = "Futures do nothing unless .awaited on."]
pub struct YieldFuture {
first_time: bool,
}
impl Future for YieldFuture {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.first_time {
self.first_time = false;
cx.waker().wake_by_ref();
Poll::Pending
} else {
Poll::Ready(())
}
}
}
#[cfg(all(
test,
any(feature = "native-tls", feature = "rustls"),
any(feature = "tokio", feature = "async-std")
))]
mod test {
use super::yield_now;
use crate::test_with_all_runtimes;
use std::sync::atomic::{AtomicBool, Ordering};
#[test]
fn test_yield() {
test_with_all_runtimes!(|_| async {
let b = AtomicBool::new(false);
use Ordering::SeqCst;
futures::join!(
async {
let mut n = 0_usize;
while n < 10 {
if b.compare_exchange(false, true, SeqCst, SeqCst).is_ok() {
n += 1;
}
yield_now().await;
}
},
async {
let mut n = 0_usize;
while n < 10 {
if b.compare_exchange(true, false, SeqCst, SeqCst).is_ok() {
n += 1;
}
yield_now().await;
}
}
);
std::io::Result::Ok(())
});
}
}