-
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 called channels.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::channel;
7
8 fn main() {
9 // channel() creates a connected pair of a sender and a
receiver.
10 // They are usually called tx and rx, which stand for
11 // "transmission" and "reception"
12 let (tx, rx) = channel();
13 for i in 0..10 {
14 // Because an mpsc channel is "Multi-producer",
15 // the sender can be cloned infinitely
16 let tx = tx.clone();
17 ...