Last active
April 26, 2024 16:05
-
-
Save esemeniuc/5373b14ed56c7f6e447135bf96807f74 to your computer and use it in GitHub Desktop.
try_recv_many()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn amain() { | |
use std::{ | |
future::poll_fn, | |
pin::Pin, | |
task::{Context, Poll}, | |
}; | |
use tokio::sync::mpsc; | |
let (tx, mut rx) = mpsc::channel(100); | |
// Spawn a thread to send messages | |
std::thread::spawn(move || { | |
let runtime = tokio::runtime::Runtime::new().unwrap(); | |
runtime.block_on(async move { | |
tx.send(1).await.unwrap(); | |
tx.send(2).await.unwrap(); | |
tx.send(3).await.unwrap(); | |
}); | |
}); | |
// Use poll_fn to read messages from the receiver | |
let mut buffer = Vec::new(); | |
let limit = 10; | |
let future = poll_fn(move |cx: &mut Context<'_>| { | |
match Pin::new(&mut rx).poll_recv_many(cx, &mut buffer, limit) { | |
Poll::Ready(count) => { | |
println!("Received {} messages", count); | |
Poll::Ready(()) | |
} | |
Poll::Pending => Poll::Pending, | |
} | |
}); | |
// Run the future to completion | |
let runtime = tokio::runtime::Runtime::new().unwrap(); | |
runtime.block_on(future); | |
// Print the received messages | |
// println!("Received messages: {:?}", buffer); | |
} | |
fn read_items(mut rx: tokio::sync::mpsc::Receiver<String>) { | |
use std::task::{Context, Poll}; | |
let waker = futures_util::task::noop_waker(); | |
let mut cx = Context::from_waker(&waker); | |
let mut items = Vec::with_capacity(10); | |
loop { | |
match rx.poll_recv_many(&mut cx, &mut items, 10) { | |
Poll::Ready(0) => { | |
println!("Channel closed, no more items"); | |
break; | |
} | |
Poll::Ready(n) => { | |
println!("Received {} items: {:?}", n, &items[..n]); | |
items.clear(); | |
} | |
Poll::Pending => { | |
println!("No items available, waiting..."); | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment