Asynchronous channels

Here is an example of a simple producer-consumer system, where the main thread produces the values 0, 1, ..., 9 and the spawned thread prints them:

// async_channels.rs

use std::thread; use std::sync::mpsc::channel; fn main() { let (tx, rx) = channel(); let join_handle = thread::spawn(move || { while let Ok(n) = rx.recv() { println!("Received {}", n); } }); for i in 0..10 { tx.send(i).unwrap(); }
join_handle.join().unwrap(); }

We first call the channel method. This returns two values, tx and rx. tx is the transmitter end, having type Sender<T> and rx is the receiver end having type Receiver<T>. Their names are just a convention and you can name them anything. Most often, you will see code bases use these names as they are concise to write.

Next, we spawn a thread that will receive values from the rx side:

    let join_handle = thread::spawn(move || {
        // Keep receiving in a loop, until tx is dropped!
        while let Ok(n) = rx.recv() { // Note: `recv()` always blocks
            println!("Received {}", n);
        }
    });

We use a while let loop. This loop will receive Err when tx is dropped. The drop happens when main returns.

 

In the preceding code, first, to create the mpsc queue, we call the channel function, which returns to us Sender<T> and Receiver<T>.

Sender<T> is a Clone type, which means it can be handed off to many threads, allowing them to send messages into the shared queue.

The multi producer, single consumer (mpsc) approach provides multiple writers but only a single reader. Both of these functions return a pair of generic types: a sender and a receiver. The sender can be used to push new things into the channel, while receivers can be used to get things from the channel. The sender implements the Clone trait while the receiver does not.

 

With the default asynchronous channels, the send method never blocks. This is because the channel buffer is infinite, so there's always space for more. Of course, it's not really infinite, just conceptually so: your system may run out of memory if you send gigabytes to the channel without receiving anything.

..................Content has been hidden....................

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