Working with channels
We can experiment with channels by rewriting our main.rs
file. First, we need to import channels and implement the main
trait for the main
function with the following code:
use tokio::sync::mpsc; #[tokio::main] async fn main() { ... }
Here, we can see that we import the mpsc
module. MPSC stands for multiple producers, single consumer channel. The name does what it says on the tin. We are going to be able to have an actor receive messages from multiple actors with mpsc
. We can now create our channel and spawn a thread that sends multiple messages to a receiver down the channel we created in our main
function with the following code:
let (tx, mut rx) = mpsc::channel(1); tokio::spawn(async move { for i in 0..10 { if let Err(e) = tx.send(i).await { println!("send error: {:?}", e)...