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:
![](https://static.packt-cdn.com/products/9781788390019/graphics/assets/4a9785ef-ce65-4879-bfb2-2dc0a0c389c4.jpg)
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...