January 2019
Beginner to intermediate
554 pages
13h 31m
English
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.rsuse 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 ...
Read now
Unlock full access