8.6 Thread Pools

CONCURRENCYSTATUS: STABLELEVEL: INTERMEDIATEREVIEWED: 2026-11-18
Before this page Processes vs Threads, Mutexes

8.6.1 Motivation

Creating a new thread is expensive. The operating system must reserve a stack, initialize thread-local storage and register the thread with the scheduler. The stack reservation is mostly address space that is committed as it is touched: on Linux its default size comes from the stack resource limit, commonly 8 MB; on Windows the Microsoft linker default is 1 MB and GNU ld’s is 2 MB; Rust’s std::thread asks for 2 MiB. If a program spawns one thread per task, and tasks are short, the overhead dominates the work.

A thread pool maintains a fixed set of worker threads that pull tasks from a queue. Workers sleep when idle, wake when work arrives, and return to the queue after each task completes. This amortizes thread creation cost over many tasks and bounds the number of threads the scheduler must manage.

The pool bounds resource consumption. An unbounded number of threads can exhaust stack space or so overload the scheduler that context switches consume more CPU than useful work.

8.6.2 The problem

The naive approach: spawn one thread per task.

tasks <- list(task1, task2, task3)
threads <- lapply(tasks, function(t) spawn_thread(t))
results <- lapply(threads, join)

If tasks arrive rapidly or complete quickly, the cost of thread creation, stack setup and scheduler bookkeeping outweighs the work. With hundreds or thousands of threads contending for a few cores, a growing share of CPU time goes to switching between them.

The pool inverts this: dedicate threads once, reuse them many times. Workers sit idle or pull from a queue, completing many tasks before the thread terminates.

8.6.3 Mental model

A thread pool is a queue with workers. Submitters (the main program or other threads) push tasks onto a shared queue. Workers run a loop: dequeue a task, execute it, store the result, repeat. When the queue empties and a shutdown signal arrives, workers exit.

Imagine a restaurant kitchen. Orders arrive on a ticket rail (the queue). Cooks (workers) pull tickets, prepare dishes, place results on the pass. Cooks do not quit after each ticket. They stay until service ends. New cooks start at opening. They do not spawn per ticket.

This mental model masks real complexity. It hides queue synchronization, shutdown coordination, work stealing when workers finish at different rates, and the choice between global vs per-worker queues.

8.6.4 Mechanism

The anatomy

A thread pool has five pieces:

  1. Task queue. A thread-safe work queue that holds submitted tasks. Submitters enqueue. Workers dequeue.
  2. Worker threads. A fixed-size set of long-lived threads. Each runs the worker loop.
  3. Result storage. A map or channel from task ID to result. Allows submitters to retrieve results asynchronously.
  4. Shutdown signal. A flag or counter that tells workers when to exit. Ensures orderly termination.
  5. Worker loop. The core logic: dequeue, execute, store result, repeat until shutdown.

The worker loop

Each worker thread runs approximately this pseudocode:

loop:
    task <- queue.dequeue_blocking()
    if task is shutdown_signal:
        break
    result <- execute(task)
    store_result(task.id, result)
    goto loop

The dequeue_blocking call is critical. If the queue is empty, the worker sleeps. When new work arrives, the queue wakes one or more sleeping workers. This prevents busy-waiting and allows workers to consume little CPU when idle.

Submission

When a submitter enqueues a task, it must wake a sleeping worker. Most queue implementations do this automatically. The submitter calls:

queue.enqueue(task)

The queue appends the task and signals a waiting worker. If the queue was empty, the worker wakes. If the queue was not empty, a worker was already awake or will check the queue soon.

flowchart LR
  submit["submitter"] --> queue[("task queue")]
  queue --> w1["worker 1"] & w2["worker 2"] & w3["worker 3"]
  w1 & w2 & w3 --> results[("results")]
  stop["shutdown signal"] -.-> queue

Thread pool architecture: submitters enqueue tasks, workers dequeue and execute, results are stored, shutdown signals drive orderly termination.

Shutdown

Shutting down a pool requires care. Submitters must stop enqueueing. The pool must wait for in-flight tasks to complete. Only then can workers exit.

Typical approach: send N shutdown signals (one per worker) to the queue. Workers dequeue signals like tasks, recognize them, and exit. This ensures all workers wake (even if the queue is empty) and terminate without orphaning tasks.

for i in 1 to num_workers:
    queue.enqueue(shutdown_signal)
for w in workers:
    join(w)

8.6.5 Tasks vs threads: the abstraction shift

In systems without pools, the programmer reasons in terms of threads. Create a thread, it does work, it terminates. Synchronization uses mutexes and condition variables explicitly.

In a pool, the programmer reasons in terms of tasks. A task is a unit of work (a function and its arguments) submitted to the pool. The pool schedules it onto a worker. This separation of concerns simplifies reasoning. The submitter does not know which thread executes the task. The worker does not know where the task came from.

This shift enables optimizations: work stealing, dynamic resizing, affinity scheduling. The pool can move tasks between workers without the submitter’s knowledge.

8.6.6 Sizing the pool

The first decision is the number of workers.

CPU-bound tasks

If tasks do not block, the pool has roughly as many workers as CPU cores. More workers do not increase throughput; they add time slicing and cache churn. On an 8-core machine, 8 workers is the usual starting point, and 16 CPU-bound workers will not finish sooner.

This assumes each task uses one core. If each task starts threads of its own (a multithreaded BLAS call, an OpenMP loop), count those threads too, and keep the total near the core count.

I/O-bound tasks

If tasks block on disk, network, or other I/O, more workers help. While one worker waits for I/O, others can run. A pool with many more workers than cores can make sense if tasks spend most of their time waiting.

Each thread still costs a stack and scheduler bookkeeping, so a pool of many thousands of threads can exhaust memory or swamp the scheduler. Coroutines or async/await (see Tokio below) multiplex many logical tasks onto fewer OS threads instead.

8.6.7 Oversubscription: the R failure mode

R runs into this through libraries that start threads of their own. R’s own reference BLAS runs on one thread, but R is often linked to OpenBLAS, MKL or Apple’s Accelerate, which are multithreaded. OpenMP code in packages does the same, and data.table uses half of the logical CPUs by default.

Consider 8 workers on an 8-core machine. Each worker calls a matrix routine in a multithreaded BLAS, which sees 8 cores and starts 8 threads. The machine now runs 8 workers times 8 BLAS threads, 64 threads on 8 cores, and the run can end up slower than with one thread per worker. The R Installation and Administration manual warns that a multithreaded BLAS can take more elapsed time than a single-threaded one, “occasionally dramatically so”.

The parallel package does nothing to limit BLAS or OpenMP threads in its workers: nothing in its R 4.6.1 source sets a thread count or calls a BLAS control. future has an opt-in option, future.fork.multithreading.enable = FALSE, that turns off OpenMP multithreading in forked workers through RhpcBLASctl; by default multithreading is allowed. A pool of 8 workers that each start 8 BLAS threads is therefore oversubscribed eightfold unless the user sets the limits.

flowchart TB
  cores["8 CPU cores"] --> workers["8 R workers,<br/>one per core"]
  workers --> blas["each starts<br/>8 BLAS threads"]
  blas --> total["64 runnable threads<br/>on 8 cores"]
  total --> thrash["context switching,<br/>throughput collapses"]

Oversubscription problem: each worker spawns nested threads internally, multiplying the thread count beyond the machine capacity.

sunlight handles this with a thread governor, on by default. When hatch() starts the pool, each worker’s BLAS, OpenMP and data.table threads are clamped to a fair share of the machine, floor(cores / n_workers) and never less than 1. The worker sets the usual environment variables, calls RhpcBLASctl when it is installed, and calls data.table::setDTthreads() when data.table is loaded. govern() changes the clamps for the whole pool between jobs.

The alternative is to set these variables by hand before starting the workers. That works too, but it fixes one value for the session, while the governor ties the clamp to the pool size and lets it change between jobs.

8.6.8 Queue design: global vs per-worker

The simplest queue design: one global queue, protected by a mutex.

Pros: Simple to implement. Submitters enqueue anywhere. Workers dequeue anywhere.

Cons: High contention. All workers and all submitters synchronize on one mutex, and as core counts grow, that lock becomes a bottleneck.

Per-worker queues: Each worker has a private queue. Submitters push to a worker’s queue (round-robin or random choice). Workers first check their own queue, then steal work from other queues if idle.

Work stealing requires a more complex data structure and coordination, but it scales. Work Stealing covers the details. Rayon (Rust’s data-parallel library) uses work stealing, and so does the multi-thread scheduler of Tokio (Rust’s async runtime), which pairs a local queue per worker with one global queue.

8.6.9 Backpressure and bounded queues

An unbounded queue can consume unbounded memory. If submitters enqueue tasks faster than workers execute them, the queue grows without limit.

Bounded queues impose a limit: if the queue is full, enqueue blocks the submitter until a worker dequeues a task and frees space. This backpressure protects memory.

A small bound prevents runaway memory but can stall the submitter often. A large bound lets bursts through but delays the feedback when work is slow. The right bound depends on how long tasks run and how much memory each one holds, so it is a value to measure, not to guess.

Bounded queues add a deadlock risk when the submitters are themselves workers: if every worker blocks on a full queue, nobody is left to drain it. A common fix is to have a submitter that finds the queue full run the task itself, which is what Java’s ThreadPoolExecutor.CallerRunsPolicy does.

8.6.10 Examples in other systems

Rayon (Rust)

Rayon is a data-parallel library. The pool uses work stealing with per-worker queues.

use rayon::prelude::*;

fn main() {
    let sum: i32 = (1..100).into_par_iter().sum();
    println!("{sum}"); // 4950
}

Rayon sizes its global pool from the RAYON_NUM_THREADS environment variable if it is set, and from the number of logical CPUs otherwise. ThreadPoolBuilder::num_threads sets the size of a custom pool, and dropping a custom ThreadPool tells its threads to finish the remaining work and exit.

Tokio (Rust)

Tokio is an async runtime for I/O-bound tasks. It multiplexes many async tasks onto a pool of OS threads.

#[tokio::main]
async fn main() {
    let a = tokio::spawn(async { 1 + 1 });
    let b = tokio::spawn(async { 2 + 2 });
    let (a, b) = (a.await.unwrap(), b.await.unwrap());
    println!("{a} {b}"); // 2 4
}

By default the multi-thread runtime starts one worker thread per CPU core, and blocking calls go to a separate pool through spawn_blocking. Many more logical tasks run concurrently than there are OS threads.

Each worker keeps a local queue of at most 256 tasks, and the runtime also keeps one global queue. A worker whose local and global queues are both empty steals half of the tasks from another worker’s local queue.

Mirai and crew (R)

R’s mirai and crew packages provide process pools, not thread pools. The pool is a set of separate background R processes, which mirai calls daemons, connected to the host session over sockets.

Each worker is a complete R interpreter. The pool architecture mirrors thread pools: a queue of tasks, submission and retrieval APIs, and worker loops that pull from the queue.

library(mirai)
m <- mirai(10 + 20)
collect_mirai(m)  # 30

Process pools avoid R interpreter thread-unsafety at the cost of serialization overhead. Each task must be serialized to send to a worker and deserialized on arrival.

8.6.11 R today

R does not have a built-in thread pool. The parallel package has process pools. makeCluster() builds the cluster that the parLapply family uses; its default type, "PSOCK", starts fresh R processes, and type = "FORK" forks them from the current session. mclapply() forks new workers on every call.

The mirai and crew packages add more orchestration on top of process pools. mirai is explicit and minimal. crew adds auto-scaling of workers and other features.

No thread-based pool exists in base R because the R interpreter is not thread-safe. Processes vs Threads explains why processes are the safe alternative.

8.6.12 The Sunlight research question

If several R interpreters can live in one process, each owned by one thread (the apartment model that threaded-r implements), a pool can hold interpreters instead of processes. Overhead would drop, and in-process communication could replace serialization.

A thread-based pool requires careful design: per-interpreter heaps, a garbage collector per interpreter, protection of global state, and a thread governor to control nested parallelism. sunlight’s prewarmed process pool tests the same pool shape one level up, with processes in place of interpreters.

One open question: does a pool of interpreters still need per-worker queues and work stealing, or is the simpler global queue sufficient? The answer depends on submitter and executor locality. If many submitters are also workers (nested parallel calls), work stealing becomes more important.

8.6.13 Relevance to my work

Threaded-R

threaded-r can host multiple interpreters in one process, and it already has a pool of them: makeCluster(type = "THREAD") gives a snow cluster whose workers are interpreters on threads. The open problems are process-wide state across the R runtime and native packages. A thread governor like sunlight’s will likely be needed to prevent oversubscription through nested BLAS and OpenMP calls.

R-in-Rust

r-in-rust can implement a thread pool without inheriting R’s thread-unsafety constraints. Each interpreter is one value owned by one thread, with its own heap and collector, so a pool of interpreters needs no shared heap to coordinate. Whether tasks can move between interpreters as freely as Rayon moves closures depends on how values cross interpreter boundaries, which is still open.

Sunlight

sunlight ships a process pool today, with the thread governor on by default to prevent oversubscription. Its governor design, its demand-driven chunk dispatch in pmap(), and its per-task L’Ecuyer-CMRG streams should carry over to a thread-based pool.

8.6.14 Tradeoffs summary

Design choice Benefit Cost
Thread pool Reuse threads across tasks, bounded resource use Synchronization complexity, queue contention at high core counts
Per-worker queues Low contention, scalable Work stealing complexity, submitter latency (round-robin or random dispatch)
Bounded queue Prevents memory runaway, backpressure Can stall the submitter, requires tuning
Process pool (R today) No thread-safe interpreter needed Serialization overhead, separate GC heaps, memory per process
Thread pool (future R) Low overhead, in-process communication Requires isolated interpreters in one process, thread governor for nested parallelism

Further reading

  • Rayon documentation. <https://docs.rs/rayon/> Work-stealing data-parallel pools.
  • Java ThreadPoolExecutor documentation. <https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html> Core and maximum pool size, the work queue and the rejection policies as named parameters.
  • Tokio runtime documentation. <https://docs.rs/tokio/latest/tokio/runtime/index.html> The multi-thread scheduler’s local and global queues and its stealing.
  • sunlight, my own R process pool with prewarming. It is not on CRAN.
  • Mirai package on CRAN. <https://cran.r-project.org/package=mirai> Minimal R process pool.
  • Crew package on CRAN. <https://cran.r-project.org/package=crew> Extended R process pool with scaling.

Where this appears

  • threaded-r Multiple interpreters in one process need to share worker capacity without creating thousands of threads per worker pool.
  • r-in-rust (rrs) Each rrs interpreter is owned by one thread, so in-process parallel work in rrs would run on a pool of interpreter threads.
  • sunlight Prewarmed process pools have the same task-queue and worker-loop anatomy as thread pools, one level up.

Where to go next

Back to top