1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use std::{future::Future, pin::Pin, task::Poll};
pub fn yield_now() -> Yield {
Yield(true)
}
pub struct Yield(bool);
impl Future for Yield {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
if self.0 {
cx.waker().wake_by_ref();
self.as_mut().0 = false;
Poll::Pending
} else {
Poll::Ready(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn tokio_test() {
use std::cell::Cell;
let x = Cell::new(0u32);
let a = async {
for _ in 0..10000 {
x.set(x.get() + 1);
yield_now().await;
}
};
let b = async {
for i in 0..10000 {
assert_eq!(x.get(), i + 1);
tokio::task::yield_now().await;
}
};
futures::future::join(a, b).await;
}
#[async_std::test]
async fn async_std_test() {
use std::cell::Cell;
let x = Cell::new(0u32);
let a = async {
for _ in 0..10000 {
x.set(x.get() + 1);
yield_now().await;
}
};
let b = async {
for i in 0..10000 {
assert_eq!(x.get(), i + 1);
async_std::task::yield_now().await;
}
};
futures::future::join(a, b).await;
}
}