ExamplesBy LevelBy TopicLearning Paths
923 Fundamental

923-thread-pool — Thread Pool

Functional Programming

Tutorial

The Problem

Spawning a new OS thread for each task is expensive: thread creation costs ~10-100 microseconds and each thread consumes stack memory. For workloads with many short tasks, the thread creation overhead dominates. A thread pool pre-creates N worker threads and reuses them for many tasks. Work is submitted to a queue; idle workers pick up and execute tasks. This is the foundation of most concurrent runtime systems: Java's Executors, Python's concurrent.futures.ThreadPoolExecutor, .NET's ThreadPool, and Rust's rayon. This example shows the manual implementation.

🎯 Learning Outcomes

  • • Implement a fixed-size thread pool using Arc<Mutex<Receiver<Task>>> for work stealing
  • • Understand Box<dyn FnOnce() + Send> as the type-erased task representation
  • • Use the Drop trait to cleanly shut down workers when the pool is dropped
  • • Recognize how a shared receiver with mutex enables fair work distribution
  • • Compare with OCaml's Thread module and Domain for work pools
  • Code Example

    #![allow(clippy::all)]
    // Placeholder — Thread Pool

    Key Differences

  • Type-erased tasks: Rust's Box<dyn FnOnce() + Send> is the idiomatic task type; OCaml uses unit -> unit functions with explicit type casting.
  • Shared receiver: Rust wraps Receiver in Arc<Mutex> for fair multi-worker distribution; OCaml uses Queue.t + Mutex + Condition explicitly.
  • Drop-based shutdown: Rust's Drop on the pool gracefully shuts down via channel closure; OCaml requires explicit Thread.join coordination.
  • rayon alternative: For CPU-bound parallel work, Rust's rayon crate provides a work-stealing thread pool as a library; OCaml's parallel library provides similar functionality.
  • OCaml Approach

    OCaml's Thread module: Thread.create f x spawns; Thread.join t waits. A pool: create N threads sharing a Queue.t protected by Mutex. OCaml 5 Domain.spawn enables parallel execution on multi-core. The Thread_pool library on opam provides a production-quality implementation. OCaml's Lwt and Eio runtimes implement work-stealing pools internally for their task schedulers. The main OCaml advantage: green threads in Lwt/Eio are cheaper than OS threads.

    Full Source

    #![allow(clippy::all)]
    // Placeholder — Thread Pool

    Deep Comparison

    923-thread-pool — Language Comparison

    std vs tokio

    Aspectstd versiontokio version
    RuntimeOS threads via std::threadAsync tasks on tokio runtime
    Synchronizationstd::sync::Mutex, Condvartokio::sync::Mutex, channels
    Channelsstd::sync::mpsc (unbounded)tokio::sync::mpsc (bounded, async)
    BlockingThread blocks on lock/recvTask yields, runtime switches tasks
    OverheadOne OS thread per taskMany tasks per thread (M:N)
    Best forCPU-bound, simple concurrencyI/O-bound, high-concurrency servers

    Exercises

  • Add a submit_with_result<T: Send>(f: impl FnOnce() -> T) -> impl Future<Output=T> method using channels.
  • Implement a priority thread pool where high-priority tasks are executed before low-priority ones.
  • Add metrics: track total tasks submitted, completed, and average wait time using atomic counters.
  • Open Source Repos