Sending data across threads
So far, we've looked at threads that work independently. Now, let's take a look at intertwined threads that need to share data. This situation is common when setting up servers, as the thread receiving client messages is usually not the same as the one that actually handles and responds to the client input. Rust gives us the concept of channels as a solution. A channel is split into a sender and a receiver which can share data across threads.
How to do it...
Open the
Cargo.toml
file that was generated earlier for you.- Under
[dependencies]
, add the following line:
rand = "0.4.2"
- If you want, you can go to rand's crates.io page (https://crates.io/crates/rand) to check for the newest version and use that one instead.
In the folder
bin
, create a file calledchannels.rs
.Add the following code and run it with
cargo run --bin channels
:
1 extern crate rand; 2 3 use rand::Rng; 4 use std::thread; 5 // mpsc stands for "Multi-producer, single-consumer" 6 use std::sync::mpsc...