56 lines
1.2 KiB
Rust
56 lines
1.2 KiB
Rust
use bachata::{Executor, JoinError};
|
|
|
|
fn main() -> Result<(), JoinError> {
|
|
Executor::new().block_on(async move {
|
|
let exec = Executor::current();
|
|
let mut handles = Vec::new();
|
|
|
|
let (tx, mut rx) = mpsc::channel();
|
|
|
|
for i in 0..10 {
|
|
let tx = tx.clone();
|
|
handles.push(exec.spawn(async move {
|
|
for j in (i * 10)..((i + 1) * 10) {
|
|
yield_now().await;
|
|
tx.send(j);
|
|
}
|
|
}));
|
|
}
|
|
drop(tx);
|
|
|
|
while let Some(val) = rx.recv().await {
|
|
println!("got {}", val);
|
|
}
|
|
|
|
for handle in handles {
|
|
handle.await?;
|
|
}
|
|
|
|
Ok(())
|
|
})
|
|
}
|
|
|
|
async fn yield_now() {
|
|
YieldNow(false).await
|
|
}
|
|
|
|
struct YieldNow(bool);
|
|
|
|
impl std::future::Future for YieldNow {
|
|
type Output = ();
|
|
|
|
fn poll(
|
|
self: std::pin::Pin<&mut Self>,
|
|
cx: &mut std::task::Context<'_>,
|
|
) -> std::task::Poll<Self::Output> {
|
|
let this = self.get_mut();
|
|
if this.0 {
|
|
return std::task::Poll::Ready(());
|
|
}
|
|
|
|
this.0 = true;
|
|
cx.waker().wake_by_ref();
|
|
std::task::Poll::Pending
|
|
}
|
|
}
|