You can find the full code for the complete example I cover in the video here: https://github.com/caveofprogramming/rust/
Sending and Receiving Messages
Rust’s ownership rules can make it difficult to have multiple threads reading and writing to some data model.
Inter-thread messaging is a very elegant alternative.
For this example you need crossbeam-channel = “0.5” in your dependencies.
In this program I use crossbeam to create an “unbounded” channel, then I send a message consisting of the value 123 down the channel. At the other end of the channel, a receiver receives the value, and we print it.
Note: the channel is “unbounded” in the sense that we can send as many messages as we like, even if they haven’t been received yet. We can also create bounded channels that limit the number of messages that can be sent when they are not being received.
You can send vectors, structs, enums and complex data structures through a crossbeam channel.
The real value of this is:
The sender and receiver do not have to exist in the same thread. They can be in different threads, and thread synchronisation problems are thereby avoided, since we’re not reading or writing shared data.
With crossbeam you can clone the sender and receiver as many times as you want, and pass them around to different functions and to different threads, just as you like. A function or thread can take ownership of the clone, but it still refers to the same channel.
For example, you can have an “update engine” thread which solely deals with a data model, and fields requests for bits of data or applies updates to the model on the basis of messages sent to it.
We can also create a “bounded” channel.
This channel will only let us send messages one at a time; each message must be received before a new one can be sent. This channel is apparently a little more lightweight, and can be used to send replies to messages containing data.
I cover both in the video, and we also see how this looks in the (more realistic) context of using threads.












