typestar

Channels in Rust

mpsc moves values between threads: many senders, one receiver.

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    for id in 0..3 {
        let tx = tx.clone();
        thread::spawn(move || {
            tx.send(format!("worker {id} finished")).unwrap();
        });
    }
    drop(tx);

    for message in rx {
        println!("{message}");
    }
}

How it works

  1. Each thread gets its own clone of the sender.
  2. The receiver iterates until every sender is dropped.
  3. Values are moved, so there is nothing to lock.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
260
Tokens
93
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 53 seconds.

Type this snippet

Step 1 of 2 in Channels, step 7 of 15 in Concurrency & async.

← Previous Next →

Channels in other languages