RRust By Example
advancedConcurrency

Thread Pool Pattern

Simple thread pool pattern with channels.

Thread Pool Pattern

Simple thread pool pattern with channels.

Difficulty

Advanced

Code

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

fn process(id: u32) -> String {
    format!("task {} done", id)
}

fn main() {
    let (tx, rx) = mpsc::channel();
    let rx = std::sync::Arc::new(std::sync::Mutex::new(rx));

    // spawn worker threads
    let mut handles = vec![];
    for worker_id in 0..4 {
        let rx = std::sync::Arc::clone(&rx);
        handles.push(thread::spawn(move || {
            loop {
                let task = rx.lock().unwrap().recv();
                match task {
                    Ok(id) => {
                        let result = process(id);
                        println!("worker {}: {}", worker_id, result);
                    }
                    Err(_) => break,
                }
            }
        }));
    }

    // send tasks
    for i in 0..8 {
        tx.send(i).unwrap();
    }
    drop(tx);

    for h in handles {
        h.join().unwrap();
    }
}

Explanation

Thread pool pattern with channels for task distribution.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the concurrency category to build a complete understanding of this topic.

More Concurrency Examples