From 3684ae79da4e98692193c561fa574a86e4b4a8da Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Sun, 20 Mar 2022 09:58:06 +0800 Subject: [PATCH] feat: add select2 --- __concurrent/async_study/examples/select2.rs | 44 ++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 __concurrent/async_study/examples/select2.rs diff --git a/__concurrent/async_study/examples/select2.rs b/__concurrent/async_study/examples/select2.rs new file mode 100644 index 0000000..b2b6b4d --- /dev/null +++ b/__concurrent/async_study/examples/select2.rs @@ -0,0 +1,44 @@ +use std::future::Future; +use std::pin::Pin; +use std::task::{Context, Poll}; +use std::time::Duration; +use tokio::sync::oneshot::{channel, Receiver}; + +#[tokio::main] +async fn main() { + let (tx1, rx1) = channel::(); + let (_tx2, rx2) = channel::(); + + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(200)).await; + let _ = tx1.send(1); + }); + + println!("start select"); + MySelect { rx1, rx2 }.await; + println!("end select"); +} + + +struct MySelect { + rx1: Receiver, + rx2: Receiver, +} + +impl Future for MySelect { + type Output = (); + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + if let Poll::Ready(val) = Pin::new(&mut self.rx1).poll(cx) { + println!("rx1 completed first with {:?}", val); + return Poll::Ready(()); + } + + if let Poll::Ready(val) = Pin::new(&mut self.rx2).poll(cx) { + println!("rx2 completed first with {:?}", val); + return Poll::Ready(()); + } + + Poll::Pending + } +}