Programming Search⌘K

Patterncore

Thread pool

Also called thread pool, worker pool, worker-crew model, replicated workers, executor.

A thread pool keeps a fixed set of worker threads that take tasks from a queue. The program pays for thread creation once and limits how many tasks run at the same time.

Family
concurrency
Intent
Keep a set of threads that wait for tasks, so that a program runs many short tasks concurrently without the cost of creating and destroying a thread for each task.
Also called
Worker pool, Worker-crew model, Replicated workers

Intent

A thread pool maintains multiple threads that wait for tasks to be allocated for concurrent execution by the supervising program.1 The pool avoids the latency of frequent creation and destruction of threads for short-lived tasks, and it can limit the load on the system.1

Problem

A server that creates a new thread for each request pays for thread creation and destruction on every request. Creating and destroying a thread and its associated resources can be an expensive process in terms of time.1 The number of threads also has no upper limit. The Rust book gives the example of a server that someone sends 10 million requests: with a thread for each request, the requests could use up all the server's resources.2

Solution

Create a fixed number of worker threads once. Requests go to the pool, and the pool keeps a queue of them.2 Each worker takes a request from the queue, handles it, and then asks the queue for the next request.2 With N workers, up to N requests run at the same time.2

The Java ThreadPoolExecutor names the parts of a general pool:3

  • The core pool size and the maximum pool size set the bounds of the number of threads. If they are the same, the pool has a fixed size.3
  • The work queue is a BlockingQueue that holds submitted tasks.3
  • When fewer than the core number of threads run, the pool adds a thread for a new task. When the core number or more run, the pool prefers to put the task in the queue.3
submit(task) --> [ task | task | task ]   work queue
                     |      |      |
                 worker1 worker2 worker3   fixed set of threads
                     |      |      |
                   result result result    (for example in a future)

In Python, ThreadPoolExecutor.submit schedules a callable and returns a Future that represents its execution.4

Example

The example submits 100 tasks to a pool of 4 workers. Each task returns the square of its number and records which worker ran it and how many tasks run at that moment.

tasks run: 100
sum of results: 328350
workers used, at most 4: True
most tasks running at once, at most 4: True

The examples for each language show the same program.

PythonGitHub
import threading
import time
from concurrent.futures import ThreadPoolExecutor

lock = threading.Lock()
running = 0
most_running = 0
workers = set()


def task(n):
    global running, most_running
    with lock:
        running += 1
        most_running = max(most_running, running)
        workers.add(threading.get_ident())
    time.sleep(0.001)
    with lock:
        running -= 1
    return n * n


with ThreadPoolExecutor(max_workers=4) as pool:
    futures = [pool.submit(task, n) for n in range(100)]
    results = [f.result() for f in futures]

print("tasks run:", len(results))
print("sum of results:", sum(results))
print("workers used, at most 4:", len(workers) <= 4)
print("most tasks running at once, at most 4:", most_running <= 4)
Output
tasks run: 100
sum of results: 328350
workers used, at most 4: True
most tasks running at once, at most 4: True
  • Verdict: stdlib. concurrent.futures.ThreadPoolExecutor is the pool, and submit returns a Future for each task.
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <functional>
#include <future>
#include <iostream>
#include <mutex>
#include <set>
#include <thread>
#include <vector>

class ThreadPool {
public:
    explicit ThreadPool(int size) {
        for (int i = 0; i < size; i++) {
            threads_.emplace_back([this] {
                for (;;) {
                    std::function<void()> work;
                    {
                        std::unique_lock<std::mutex> lock(mutex_);
                        ready_.wait(lock, [this] { return stopping_ || !queue_.empty(); });
                        if (queue_.empty()) return;
                        work = std::move(queue_.front());
                        queue_.pop_front();
                    }
                    work();
                }
            });
        }
    }

    template <typename F>
    auto submit(F fn) -> std::future<decltype(fn())> {
        auto task = std::make_shared<std::packaged_task<decltype(fn())()>>(fn);
        {
            std::lock_guard<std::mutex> lock(mutex_);
            queue_.emplace_back([task] { (*task)(); });
        }
        ready_.notify_one();
        return task->get_future();
    }

    ~ThreadPool() {
        {
            std::lock_guard<std::mutex> lock(mutex_);
            stopping_ = true;
        }
        ready_.notify_all();
        for (auto& t : threads_) t.join();
    }

private:
    std::vector<std::thread> threads_;
    std::deque<std::function<void()>> queue_;
    std::mutex mutex_;
    std::condition_variable ready_;
    bool stopping_ = false;
};

std::atomic<int> running{0};
std::atomic<int> most_running{0};
std::mutex workers_mutex;
std::set<std::thread::id> workers;

long long task(long long n) {
    int now = ++running;
    int seen = most_running.load();
    while (seen < now && !most_running.compare_exchange_weak(seen, now)) {
    }
    {
        std::lock_guard<std::mutex> lock(workers_mutex);
        workers.insert(std::this_thread::get_id());
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
    --running;
    return n * n;
}

int main() {
    std::vector<std::future<long long>> futures;
    long long sum = 0;
    {
        ThreadPool pool(4);
        for (long long n = 0; n < 100; n++) {
            futures.push_back(pool.submit([n] { return task(n); }));
        }
        for (auto& f : futures) sum += f.get();
    }
    std::cout << "tasks run: " << futures.size() << "\n";
    std::cout << "sum of results: " << sum << "\n";
    std::cout << "workers used, at most 4: " << (workers.size() <= 4 ? "True" : "False") << "\n";
    std::cout << "most tasks running at once, at most 4: " << (most_running <= 4 ? "True" : "False") << "\n";
}
Output
tasks run: 100
sum of results: 328350
workers used, at most 4: True
most tasks running at once, at most 4: True
  • Verdict: idiom. ThreadPool is a small class: 4 threads wait on a condition_variable for functions in a deque, and submit returns a std::future from a std::packaged_task.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static final AtomicInteger running = new AtomicInteger();
    static final AtomicInteger mostRunning = new AtomicInteger();
    static final Set<String> workers = ConcurrentHashMap.newKeySet();

    static long task(long n) throws InterruptedException {
        int now = running.incrementAndGet();
        mostRunning.accumulateAndGet(now, Math::max);
        workers.add(Thread.currentThread().getName());
        Thread.sleep(1);
        running.decrementAndGet();
        return n * n;
    }

    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(4);
        List<Future<Long>> futures = new ArrayList<>();
        for (long n = 0; n < 100; n++) {
            final long k = n;
            futures.add(pool.submit(() -> task(k)));
        }
        long sum = 0;
        for (Future<Long> f : futures) {
            sum += f.get();
        }
        pool.shutdown();
        System.out.println("tasks run: " + futures.size());
        System.out.println("sum of results: " + sum);
        System.out.println("workers used, at most 4: " + (workers.size() <= 4 ? "True" : "False"));
        System.out.println("most tasks running at once, at most 4: " + (mostRunning.get() <= 4 ? "True" : "False"));
    }
}
Output
tasks run: 100
sum of results: 328350
workers used, at most 4: True
most tasks running at once, at most 4: True
  • Verdict: stdlib. Executors.newFixedThreadPool(4) creates the pool, and submit returns a Future for each task.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

class FixedThreadPool
{
    private readonly BlockingCollection<Action> queue = new BlockingCollection<Action>();
    private readonly List<Thread> threads = new List<Thread>();

    public FixedThreadPool(int size)
    {
        for (int i = 0; i < size; i++)
        {
            var t = new Thread(() =>
            {
                foreach (var work in queue.GetConsumingEnumerable())
                {
                    work();
                }
            });
            t.Start();
            threads.Add(t);
        }
    }

    public Task<T> Submit<T>(Func<T> fn)
    {
        var tcs = new TaskCompletionSource<T>();
        queue.Add(() => tcs.SetResult(fn()));
        return tcs.Task;
    }

    public void Shutdown()
    {
        queue.CompleteAdding();
        foreach (var t in threads) t.Join();
    }
}

class Program
{
    static int running = 0;
    static int mostRunning = 0;
    static readonly ConcurrentDictionary<int, bool> workers = new ConcurrentDictionary<int, bool>();

    static long Work(long n)
    {
        int now = Interlocked.Increment(ref running);
        int seen;
        while ((seen = Volatile.Read(ref mostRunning)) < now &&
               Interlocked.CompareExchange(ref mostRunning, now, seen) != seen) { }
        workers.TryAdd(Environment.CurrentManagedThreadId, true);
        Thread.Sleep(1);
        Interlocked.Decrement(ref running);
        return n * n;
    }

    static void Main()
    {
        var pool = new FixedThreadPool(4);
        var futures = new List<Task<long>>();
        for (long n = 0; n < 100; n++)
        {
            long k = n;
            futures.Add(pool.Submit(() => Work(k)));
        }
        long sum = 0;
        foreach (var f in futures) sum += f.Result;
        pool.Shutdown();
        Console.WriteLine("tasks run: " + futures.Count);
        Console.WriteLine("sum of results: " + sum);
        Console.WriteLine("workers used, at most 4: " + (workers.Count <= 4));
        Console.WriteLine("most tasks running at once, at most 4: " + (mostRunning <= 4));
    }
}
Output
tasks run: 100
sum of results: 328350
workers used, at most 4: True
most tasks running at once, at most 4: True
  • Verdict: idiom. FixedThreadPool is a small class: 4 threads take actions from a BlockingCollection, and each Submit returns a Task completed by a TaskCompletionSource.
JavaScriptGitHub
const { Worker } = require("node:worker_threads");

// Each worker thread runs one task at a time.
const workerCode = `
const { parentPort, threadId } = require("node:worker_threads");
const pause = new Int32Array(new SharedArrayBuffer(4));
parentPort.on("message", (n) => {
  if (n === null) {
    parentPort.close();
    return;
  }
  Atomics.wait(pause, 0, 0, 1); // a short blocking call
  parentPort.postMessage({ threadId, result: n * n });
});
parentPort.postMessage({ threadId, result: null });
`;

const tasks = Array.from({ length: 100 }, (_, n) => n); // the work queue
const idle = [];
const workersUsed = new Set();
let running = 0;
let mostRunning = 0;
const results = [];

function dispatch() {
  while (idle.length > 0) {
    const worker = idle.shift();
    if (tasks.length > 0) {
      running += 1;
      mostRunning = Math.max(mostRunning, running);
      worker.postMessage(tasks.shift());
    } else {
      worker.postMessage(null);
    }
  }
}

const exits = [];
for (let i = 0; i < 4; i++) {
  const worker = new Worker(workerCode, { eval: true });
  worker.on("message", ({ threadId, result }) => {
    if (result !== null) {
      running -= 1;
      workersUsed.add(threadId);
      results.push(result);
    }
    idle.push(worker);
    dispatch();
  });
  exits.push(new Promise((resolve) => worker.on("exit", resolve)));
}

Promise.all(exits).then(() => {
  console.log("tasks run:", results.length);
  console.log("sum of results:", results.reduce((a, b) => a + b, 0));
  console.log("workers used, at most 4:", workersUsed.size <= 4 ? "True" : "False");
  console.log("most tasks running at once, at most 4:", mostRunning <= 4 ? "True" : "False");
});
Output
tasks run: 100
sum of results: 328350
workers used, at most 4: True
most tasks running at once, at most 4: True
  • Verdict: idiom. The main thread keeps the work queue and hands each task to an idle worker_threads worker.
TypeScriptGitHub
import { Worker } from "node:worker_threads";

// Each worker thread runs one task at a time.
const workerCode = `
const { parentPort, threadId } = require("node:worker_threads");
const pause = new Int32Array(new SharedArrayBuffer(4));
parentPort.on("message", (n) => {
  if (n === null) {
    parentPort.close();
    return;
  }
  Atomics.wait(pause, 0, 0, 1); // a short blocking call
  parentPort.postMessage({ threadId, result: n * n });
});
parentPort.postMessage({ threadId, result: null });
`;

const tasks: number[] = Array.from({ length: 100 }, (_, n) => n); // the work queue
const idle: Worker[] = [];
const workersUsed = new Set<number>();
let running = 0;
let mostRunning = 0;
const results: number[] = [];

function dispatch(): void {
  while (idle.length > 0) {
    const worker = idle.shift();
    if (tasks.length > 0) {
      running += 1;
      mostRunning = Math.max(mostRunning, running);
      worker.postMessage(tasks.shift());
    } else {
      worker.postMessage(null);
    }
  }
}

const exits: Promise<number>[] = [];
for (let i = 0; i < 4; i++) {
  const worker = new Worker(workerCode, { eval: true });
  worker.on("message", ({ threadId, result }: { threadId: number; result: number | null }) => {
    if (result !== null) {
      running -= 1;
      workersUsed.add(threadId);
      results.push(result);
    }
    idle.push(worker);
    dispatch();
  });
  exits.push(new Promise((resolve) => worker.on("exit", resolve)));
}

Promise.all(exits).then(() => {
  console.log("tasks run:", results.length);
  console.log("sum of results:", results.reduce((a, b) => a + b, 0));
  console.log("workers used, at most 4:", workersUsed.size <= 4 ? "True" : "False");
  console.log("most tasks running at once, at most 4:", mostRunning <= 4 ? "True" : "False");
});
Output
tasks run: 100
sum of results: 328350
workers used, at most 4: True
most tasks running at once, at most 4: True
  • Verdict: idiom. The main thread keeps the work queue and hands each task to an idle worker_threads worker.
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
	"time"
)

type job struct {
	n      int
	result chan int
}

var running, mostRunning atomic.Int64

func task(n int) int {
	now := running.Add(1)
	for {
		seen := mostRunning.Load()
		if seen >= now || mostRunning.CompareAndSwap(seen, now) {
			break
		}
	}
	time.Sleep(time.Millisecond)
	running.Add(-1)
	return n * n
}

func main() {
	jobs := make(chan job) // the work queue
	var mu sync.Mutex
	workersUsed := map[int]bool{}
	var wg sync.WaitGroup
	for id := 0; id < 4; id++ { // a fixed number of worker goroutines
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			for j := range jobs {
				mu.Lock()
				workersUsed[id] = true
				mu.Unlock()
				j.result <- task(j.n)
			}
		}(id)
	}

	results := make([]chan int, 100)
	for n := range results {
		results[n] = make(chan int, 1)
	}
	go func() {
		for n := range results {
			jobs <- job{n, results[n]}
		}
		close(jobs)
	}()

	sum := 0
	for _, r := range results {
		sum += <-r
	}
	wg.Wait()
	fmt.Println("tasks run:", len(results))
	fmt.Println("sum of results:", sum)
	fmt.Println("workers used, at most 4:", boolText(len(workersUsed) <= 4))
	fmt.Println("most tasks running at once, at most 4:", boolText(mostRunning.Load() <= 4))
}

func boolText(b bool) string {
	if b {
		return "True"
	}
	return "False"
}
Output
tasks run: 100
sum of results: 328350
workers used, at most 4: True
most tasks running at once, at most 4: True
  • Verdict: idiom. A fixed number of goroutines read from the jobs channel, the form that Effective Go gives, and each job carries a channel for its result.
RustGitHub
use std::collections::HashSet;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

type Job = Box<dyn FnOnce(usize) + Send + 'static>;

struct ThreadPool {
    workers: Vec<thread::JoinHandle<()>>,
    sender: Option<mpsc::Sender<Job>>,
}

impl ThreadPool {
    fn new(size: usize) -> ThreadPool {
        let (sender, receiver) = mpsc::channel::<Job>();
        let receiver = Arc::new(Mutex::new(receiver));
        let workers = (0..size)
            .map(|id| {
                let receiver = Arc::clone(&receiver);
                thread::spawn(move || loop {
                    let message = receiver.lock().unwrap().recv();
                    match message {
                        Ok(job) => job(id),
                        Err(_) => break, // the pool was dropped
                    }
                })
            })
            .collect();
        ThreadPool { workers, sender: Some(sender) }
    }

    fn execute<F: FnOnce(usize) + Send + 'static>(&self, f: F) {
        self.sender.as_ref().unwrap().send(Box::new(f)).unwrap();
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        drop(self.sender.take());
        for worker in self.workers.drain(..) {
            worker.join().unwrap();
        }
    }
}

fn main() {
    let running = Arc::new(AtomicUsize::new(0));
    let most_running = Arc::new(AtomicUsize::new(0));
    let workers_used = Arc::new(Mutex::new(HashSet::new()));
    let (results_tx, results_rx) = mpsc::channel();
    {
        let pool = ThreadPool::new(4);
        for n in 0..100u64 {
            let (running, most_running) = (Arc::clone(&running), Arc::clone(&most_running));
            let workers_used = Arc::clone(&workers_used);
            let results_tx = results_tx.clone();
            pool.execute(move |id| {
                let now = running.fetch_add(1, Ordering::SeqCst) + 1;
                most_running.fetch_max(now, Ordering::SeqCst);
                workers_used.lock().unwrap().insert(id);
                thread::sleep(Duration::from_millis(1));
                running.fetch_sub(1, Ordering::SeqCst);
                results_tx.send(n * n).unwrap();
            });
        }
    } // dropping the pool waits for the workers
    drop(results_tx);
    let results: Vec<u64> = results_rx.iter().collect();
    let cap = |b: bool| if b { "True" } else { "False" };
    println!("tasks run: {}", results.len());
    println!("sum of results: {}", results.iter().sum::<u64>());
    println!("workers used, at most 4: {}", cap(workers_used.lock().unwrap().len() <= 4));
    println!("most tasks running at once, at most 4: {}", cap(most_running.load(Ordering::SeqCst) <= 4));
}
Output
tasks run: 100
sum of results: 328350
workers used, at most 4: True
most tasks running at once, at most 4: True
  • Verdict: idiom. ThreadPool follows the Rust book: workers share the receiving end of an mpsc channel behind Arc<Mutex<_>>, and dropping the pool closes the channel and joins the workers.

Consequences

Benefits:

  • Thread creation and destruction overhead is restricted to the initial creation of the pool, which may result in better performance and better system stability.1
  • The pool bounds and manages the resources, including threads, that a collection of tasks uses.3
  • A pool can make it simple to queue work and to control concurrency at a higher level than manual management of threads.1

Liabilities:

  • The size must be tuned. An excessive number of threads in reserve wastes memory, and context switches between runnable threads cost performance.1
  • An unbounded queue admits the possibility of unbounded work queue growth when tasks arrive on average faster than the pool processes them.3
  • A task that waits for another task in the same pool can deadlock. The Python documentation shows a pool with one worker that runs a function which submits a second task and waits for its result: the second task never runs.4

This code runs but gives a wrong answer on purpose.

from concurrent.futures import ThreadPoolExecutor, TimeoutError

pool = ThreadPoolExecutor(max_workers=1)


def inner():
    return "inner done"


def outer():
    f = pool.submit(inner)  # queued behind outer: no free worker
    try:
        return f.result(timeout=0.5)
    except TimeoutError:
        return "outer timed out: the only worker waits for itself"


print(pool.submit(outer).result())
pool.shutdown()
Output
outer timed out: the only worker waits for itself

The example uses a timeout so that it ends. Without the timeout, the program never ends.

When not to use it

A pool saves work when the program runs many short-lived tasks.1 A few threads that live as long as the program gain little from it. Do not put tasks that wait for each other into a small pool. The Java documentation recommends a direct hand-off queue, which creates a new thread when no thread is free, for sets of requests that might have internal dependencies.3

  • Fixed, cached and single pools. Java's Executors class has factory methods for an unbounded pool with automatic thread reclamation, a fixed-size pool and a single background thread.3
  • Queue strategies. A ThreadPoolExecutor can use a direct hand-off, an unbounded queue or a bounded queue. A bounded queue helps prevent resource exhaustion, but it can be more difficult to tune.3
  • Worker goroutines. In Go, a server can start a fixed number of goroutines that all read from the request channel. The number of goroutines limits the number of simultaneous calls.5
  • Dynamic size. A ThreadPoolExecutor adjusts its size between the core and maximum bounds. Threads above the core size end when they are idle for longer than the keep-alive time.3

A bounded submission makes the caller wait when the pool has too many tasks. The example limits the pool to 4 tasks that wait or run:

import threading
import time
from concurrent.futures import ThreadPoolExecutor


class BoundedExecutor:
    def __init__(self, workers, limit):
        self.pool = ThreadPoolExecutor(max_workers=workers)
        self.slots = threading.Semaphore(limit)

    def submit(self, fn, *args):
        self.slots.acquire()  # the caller waits when the queue is full
        f = self.pool.submit(fn, *args)
        f.add_done_callback(lambda _: self.slots.release())
        return f


outstanding = 0
most = 0


def task(n):
    time.sleep(0.01)
    return n


ex = BoundedExecutor(workers=2, limit=4)
futures = []
for n in range(20):
    f = ex.submit(task, n)
    outstanding = sum(not g.done() for g in futures) + 1
    most = max(most, outstanding)
    futures.append(f)
ex.pool.shutdown()
print("tasks done:", sum(f.done() for f in futures))
print("tasks queued or running at once, at most 4:", most <= 4)
Output
tasks done: 20
tasks queued or running at once, at most 4: True

Half-Sync/Half-Async uses a pool as its synchronous layer. Leader/Followers is a pool in which the threads take turns to wait for events, without a queue between them. An Object Pool applies the same idea to objects other than threads.

Known uses

  • Java: ThreadPoolExecutor and ScheduledThreadPoolExecutor provide tunable, flexible thread pools.3
  • Python: concurrent.futures.ThreadPoolExecutor. The default number of workers is min(32, (os.process_cpu_count() or 1) + 4).4
  • libuv, a library that was originally written for Node.js, runs blocking file I/O operations in a thread pool, while network I/O stays on the loop's thread.6
  • The Rust book builds a ThreadPool type for its web server project.2

References

  1. Thread pool, Wikipedia, lead; Performance; In languages
  2. The Rust Programming Language, 21.2 From Single-Threaded to Multithreaded Server, Improving Throughput with a Thread Pool
  3. ThreadPoolExecutor, Java SE 21 API documentation, class description; Core and maximum pool sizes; Queuing
  4. concurrent.futures, Launching parallel tasks, Python documentation, Executor Objects; ThreadPoolExecutor
  5. Effective Go, Channels
  6. Design overview, libuv documentation, The I/O loop; File I/O

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source