I'd like to read from two streams simultaneously using async. Here's an example:
use async_std::os::unix::net::UnixStream;
use async_std::io::BufReader;
use async_std::prelude::*;
use async_std::task;
use std::sync::Arc;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
// handle log connection
async fn read_log(id: &str) -> Result<()> {
let mut stream = UnixStream::connect(format!("/logger{}.sock", id)).await?;
let reader = BufReader::new(&stream);
let mut lines = reader.lines();
while let Some(line) = lines.next().await {
let line = line.unwrap();
println!("{}={}", id, line); // print or send to redis
}
Ok(())
}
// start 2 concurrent persistent connections
async fn start_logs() -> Result<()> {
task::spawn(read_log("1"));
task::spawn(read_log("2"));
Ok(())
}
// start app
fn main() -> Result<()> {
task::block_on(
start_logs()
)
}
I'd like to simulate multiple threads where all write to the same stdout. In the example above, the program stops immediately and does not wait for tasks to complete. I could call task::spawn(read_log("1")).await;
instead but it would never complete and start the task::spawn(read_log("2"))
. What's the right way to handle multiple streams concurrently using async/await?