Communication through channels
Data can also be exchanged between threads by passing messages among them. This is implemented in Rust by channels, which are like unidirectional pipes that connect two threads; data is processed first-in, first-out.
Data flows over this channel between two endpoints: from the Sender<T>
to the Receiver<T>
, both of which are generic and take the type T
of the message to be transferred (which obviously must be the same for the Sender
and Receiver
). In this mechanism, a copy of the data to share is made for the receiving thread, so you wouldn't want to use this for very large data:
To create a channel, we need to import the mpsc
submodule from std::sync (mpsc
, which stands for multi-producer, single-consumer communication primitives, and then use the channel()
method:
// code from Chapter 9/code/channels.rs: use std::thread; use std::sync::mpsc::channel;use std::sync::mpsc::{Sender, Receiver}; fn main() { let (tx, rx): (Sender<i32>, Receiver...