Reputation: 223
Here is a simple example from the book "Rust Essentials - A Comprehensive Guide (2024)" that demonstrates concurrent reading from 2 threads into the main
using channels and select!
macro. Unfortunately, the Rust Playground reports an error "no method named next
found for struct futures::stream::Iter
".
Note that the issue in this sample is not intended to be resolved using functions from the tokio
crate as in a similar issue here.
use futures::select;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx1, rx1) = mpsc::channel();
let (tx2, rx2) = mpsc::channel();
thread::spawn(move || {
thread::sleep(Duration::from_secs(2));
tx1.send("Message from thread 1").unwrap();
});
thread::spawn(move || {
thread::sleep(Duration::from_secs(1));
tx2.send("Message from thread 2").unwrap();
});
let mut rx1 = futures::stream::iter(rx1.iter());
let mut rx2 = futures::stream::iter(rx2.iter());
futures::executor::block_on(async {
loop {
select! {
msg = rx1.next() => println!("Received on rx1: {:?}", msg),
msg = rx2.next() => println!("Received on rx2: {:?}", msg),
complete => break,
}
}
});
}
Upvotes: 0
Views: 50