Thread synchronization

The best way to think of a channel is to see it as a walkie-talkie. At one end you have the transmitter (send) and at the other end, the receiver:

use std::thread; 
use std::sync::mpsc; 
 
fn main() { 
    // tx = transmission = sender 
    // rx = receiver 
    let (tx, rx) = mpsc::channel(); 
 
    for i in 0..10  
    { 
        let tx = tx.clone(); 
 
        thread::spawn(move ||  
        { 
            let answer = (i * 2) * i; 
 
            tx.send(answer).unwrap(); 
        }); 
    } 
 
    for _ in 0..10  
    { 
        println!("{}", rx.recv().unwrap()); 
    } 
} 
The code for this example is in Chapter 11/channels.

When we run this, we get the following:

Figure 13
..................Content has been hidden....................

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