Rust by Example

18.2 Channels

Rust provides asynchronous channels for communication between threads. Channels allow a unidirectional flow of information between two end-points: the Sender and the Receiver.

use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;

fn main() {
// Channels have two endpoints: the Sender<T> and the Receiver<T>,
// where T is the type of the message to be transferred
// (type annotation is superfluous)
let (tx, rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();

// The sender endpoint can be copied

// Each thread will send its id via the channel
// The thread takes ownership over thread_tx
// Each thread queues a message in the channel

// Sending is a non-blocking operation, the thread will continue
// immediately after sending its message
});
}

// Here, all the messages are collected
let mut ids = Vec::with_capacity(NTHREADS as usize);
// The recv method picks a message from the channel
// recv will block the current thread if there no messages available
}