How to do it...

  1. Open the Cargo.toml file that was  generated earlier for you.

  2. Under [dependencies], add the following line:
rand = "0.4.2"
  1. 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.
  2. In the folder bin, create a file called channels.rs.

  3. 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 thread::spawn(move || {
18 println!("sending: {}", i);
19 // send() pushes arbitrary data to the connected
receiver
20 tx.send(i).expect("Disconnected from receiver");
21 });
22 }
23 for _ in 0..10 {
24 // recv() blocks the current thread
25 // until a message was received
26 let msg = rx.recv().expect("Disconnected from sender");
27 println!("received: {}", msg);
28 }
29
30 let (tx, rx) = channel();
31 const DISCONNECT: &str = "Goodbye!";
32 // The following thread will send random messages
33 // until a goodbye message was sent
34 thread::spawn(move || {
35 let mut rng = rand::thread_rng();
36 loop {
37 let msg = match rng.gen_range(0, 5) {
38 0 => "Hi",
39 1 => DISCONNECT,
40 2 => "Howdy there, cowboy",
41 3 => "How are you?",
42 4 => "I'm good, thanks",
43 _ => unreachable!(),
44 };
45 println!("sending: {}", msg);
46 tx.send(msg).expect("Disconnected from receiver");
47 if msg == DISCONNECT {
48 break;
49 }
50 }
51 });
52
53 // An iterator over messages in a receiver is infinite.
54 // It will block the current thread until a message is
available
55 for msg in rx {
56 println!("received: {}", msg);
57 }
58 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.195.29