typestar

A worker pool in Rust

Jobs down one channel, results back up another — a pool in twenty lines.

use std::sync::{mpsc, Arc, Mutex};
use std::thread;

fn main() {
    let (jobs_tx, jobs_rx) = mpsc::channel::<u64>();
    let (out_tx, out_rx) = mpsc::channel::<(u64, u64)>();
    let jobs_rx = Arc::new(Mutex::new(jobs_rx));

    for _ in 0..3 {
        let jobs_rx = Arc::clone(&jobs_rx);
        let out_tx = out_tx.clone();
        thread::spawn(move || loop {
            let job = match jobs_rx.lock().unwrap().recv() {
                Ok(job) => job,
                Err(_) => break,
            };
            let squared = job * job;
            out_tx.send((job, squared)).unwrap();
        });
    }
    drop(out_tx);

    for n in 1..=6 {
        jobs_tx.send(n).unwrap();
    }
    drop(jobs_tx);

    let mut results: Vec<(u64, u64)> = out_rx.iter().collect();
    results.sort();
    println!("{:?}", results);
}

How it works

  1. The job channel is shared behind an Arc<Mutex<Receiver>>.
  2. Each worker loops until the job channel closes.
  3. Results arrive in completion order, not job order.

Keywords and builtins used here

The run, in numbers

Lines
31
Characters to type
658
Tokens
245
Three-star pace
105 tpm

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

Type this snippet

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

← Previous Next →