Thread Pools
A thread pool creates a fixed set of worker threads once and feeds them tasks through a queue. It removes the cost of creating a thread per task and puts a ceiling on how many run at once.
Workers Created Once, Fed by a Queue
- Create – start N worker threads once, when the pool is created.
- Submit – the program puts a task in the pool's task queue and gets back a future for its result.
- Execute – an idle worker removes the next task from the queue and runs it.
- Reuse – when the task ends, the worker does not exit; it takes the next task or sleeps until one arrives.
- Shut down – the pool tells every worker to stop once the queued tasks are done, and joins them.
A thread pool is a group of pre-created worker threads that wait for tasks and execute them. Instead of creating a new thread for every request and destroying it afterwards, a program submits each task to the pool; an idle worker picks it up, runs it, and goes back to wait for the next one.
In operating systems textbooks this is a form of implicit threading: the programmer identifies tasks that can run in parallel, and a library or runtime decides which thread runs each one. Fork-join, OpenMP and Apple's Grand Central Dispatch are other forms of the same idea.
- Worker thread: a long-lived thread that runs one task after another
- Task queue: holds submitted tasks until a worker is free
- Future: a handle for a result that will exist later
The Worker Loop and the Task Queue
The heart of every pool is the worker loop: take a task from the queue, run it, repeat. When the queue is empty, workers block on it, using no CPU. When a task is submitted, the queue wakes exactly one sleeping worker. This is the producer–consumer pattern, with the program as producer and the workers as consumers.
The queue is protected by a mutex and two condition variables, one for not empty (workers wait on it) and one for not full (producers wait on it when the queue is bounded). The C++ listing below shows these explicitly; Python's queue.Queue and Java's ArrayBlockingQueue contain the same machinery.
- submit() – wraps the task with a future, enqueues it and returns at once
- Future – lets the caller wait for, and read, the task's result or exception
- shutdown() – stops accepting tasks, lets workers finish the queue, then joins them
- Idle workers block on the queue; they do not spin
- Tasks start in submission order, but can finish in any order
- Results are matched to tasks by their futures, not by finishing order
Thread per Task vs a Pool
Creating a thread is not free. The kernel must allocate a thread control block and a stack, often 1 to 8 MB of reserved address space, and the scheduler must track it. For a task that runs for a few microseconds, creating and destroying a thread can cost more than the task itself. The diagram shows the difference: thread per task pays create and exit on every task, a pool pays it once.
The second reason is bounding concurrency. A server that creates a thread per request will create 10,000 threads under 10,000 simultaneous requests, exhausting memory and spending its time context switching between them. A pool of 16 threads runs at most 16 tasks at once; the rest wait in the queue, and the system degrades gracefully instead of collapsing.
| Aspect | Thread per task | Thread pool |
|---|---|---|
| Thread creation | once per task | once per worker, at startup |
| Start-up latency per task | includes creating a thread | none: a worker is already waiting |
| Threads alive under heavy load | unbounded, one per task | at most the pool size |
| Memory use | grows with load | fixed by pool size and queue length |
| Behaviour under overload | thrashing or out of memory | tasks queue up, or are rejected |
- Pools amortise thread creation across many short tasks
- The pool size is a hard limit on parallelism and memory
- Long-running, independent activities may still deserve their own thread
Terms, operations, and practical uses
Core vocabulary
- Thread poolA fixed set of reusable worker threads fed by a task queue.
- Worker threadA thread that loops: take a task, run it, take the next.
- FutureA placeholder for a task's result, filled in when the task completes.
- BackpressureSlowing producers when the queue is full, instead of growing it without limit.
Sizing and policies
- CPU-bound sizeAbout N_cores, or N_cores + 1
- I/O-bound sizeN_cores × U × (1 + W / C)
- Rejection policiesBlock, abort, caller runs, discard, discard oldest
- Starvation deadlockTasks wait on tasks in the same pool with no worker free to run them
Related lessons
- Processes and ThreadsWhat a thread is, and what it costs to create.
- Producer–Consumer ProblemThe bounded buffer every pool's task queue is built on.
- Mutexes, Semaphores, and MonitorsThe locks and condition variables inside the task queue.
- Context SwitchingThe per-switch cost that too many threads multiply.
A fixed pool of 3 workers with a bounded queue
import queue
import threading
from concurrent.futures import Future
class ThreadPool:
def __init__(self, workers, capacity):
# A bounded queue: submit() blocks while it is full, slowing the producer.
self.tasks = queue.Queue(maxsize=capacity)
self.threads = [threading.Thread(target=self._worker) for _ in range(workers)]
for t in self.threads:
t.start()
def _worker(self):
while True:
item = self.tasks.get() # sleeps while the queue is empty
if item is None: # shutdown sentinel
return
fn, args, future = item
try:
future.set_result(fn(*args))
except Exception as e:
future.set_exception(e)
def submit(self, fn, *args):
future = Future()
self.tasks.put((fn, args, future))
return future
def shutdown(self):
for _ in self.threads:
self.tasks.put(None) # one sentinel per worker
for t in self.threads:
t.join()
def is_prime(n):
return n >= 2 and all(n % d for d in range(2, int(n**0.5) + 1))
def count_primes(lo, hi):
return sum(1 for n in range(lo, hi) if is_prime(n))
# Count the primes below 13000 in seven chunks of unequal size.
chunks = [
(0, 3000),
(3000, 4000),
(4000, 6000),
(6000, 8000),
(8000, 9000),
(9000, 12000),
(12000, 13000),
]
pool = ThreadPool(workers=3, capacity=3)
futures = [pool.submit(count_primes, lo, hi) for lo, hi in chunks]
# result() waits for each task: output follows submission order, not finishing order.
results = [f.result() for f in futures]
pool.shutdown()
for i, ((lo, hi), r) in enumerate(zip(chunks, results), start=1):
print(f"T{i}: primes in [{lo}, {hi}) = {r}")
print(f"total primes below 13000 = {sum(results)}")
print(f"threads created: {len(pool.threads)} for {len(chunks)} tasks")#include <algorithm>
#include <cstdio>
#include <condition_variable>
#include <functional>
#include <future>
#include <mutex>
#include <queue>
#include <thread>
#include <utility>
#include <vector>
using namespace std;
class ThreadPool {
public:
ThreadPool(size_t workers, size_t capacity) : capacity_(capacity) {
for (size_t i = 0; i < workers; i++) threads_.emplace_back([this] { work(); });
}
// Blocks while the queue is full, which slows the producer down.
template <class F>
auto submit(F fn) -> future<decltype(fn())> {
auto task = make_shared<packaged_task<decltype(fn())()>>(std::move(fn));
auto result = task->get_future();
{
unique_lock<mutex> lock(m_);
notFull_.wait(lock, [this] { return tasks_.size() < capacity_; });
tasks_.push([task] { (*task)(); });
}
notEmpty_.notify_one();
return result;
}
void shutdown() {
{
lock_guard<mutex> lock(m_);
stopping_ = true;
}
notEmpty_.notify_all();
for (thread& t : threads_) t.join();
}
size_t size() const { return threads_.size(); }
private:
void work() {
while (true) {
function<void()> task;
{
unique_lock<mutex> lock(m_);
// Sleep while there is nothing to do.
notEmpty_.wait(lock, [this] { return stopping_ || !tasks_.empty(); });
if (tasks_.empty()) return; // stopping, and every task has been taken
task = std::move(tasks_.front());
tasks_.pop();
}
notFull_.notify_one();
task();
}
}
size_t capacity_;
vector<thread> threads_;
queue<function<void()>> tasks_;
mutex m_;
condition_variable notEmpty_, notFull_;
bool stopping_ = false;
};
int countPrimes(int lo, int hi) {
int count = 0;
for (int n = max(lo, 2); n < hi; n++) {
bool prime = true;
for (int d = 2; d * d <= n && prime; d++) prime = n % d != 0;
count += prime;
}
return count;
}
int main() {
// Count the primes below 13000 in seven chunks of unequal size.
vector<pair<int, int>> chunks = {{0, 3000}, {3000, 4000}, {4000, 6000}, {6000, 8000},
{8000, 9000}, {9000, 12000}, {12000, 13000}};
ThreadPool pool(3, 3);
vector<future<int>> futures;
for (auto c : chunks) futures.push_back(pool.submit([c] { return countPrimes(c.first, c.second); }));
// get() waits for each task, so output follows submission order, not finishing order.
int total = 0;
for (size_t i = 0; i < chunks.size(); i++) {
int r = futures[i].get();
total += r;
printf("T%zu: primes in [%d, %d) = %d\n", i + 1, chunks[i].first, chunks[i].second, r);
}
pool.shutdown();
printf("total primes below 13000 = %d\n", total);
printf("threads created: %zu for %zu tasks\n", pool.size(), chunks.size());
return 0;
}import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Main {
static class ThreadPool {
private static final Runnable STOP = () -> {}; // shutdown sentinel
private final BlockingQueue<Runnable> tasks;
private final List<Thread> threads = new ArrayList<>();
ThreadPool(int workers, int capacity) {
// A bounded queue: submit() blocks while it is full, which slows the producer down.
tasks = new ArrayBlockingQueue<>(capacity);
for (int i = 0; i < workers; i++) {
Thread t = new Thread(this::work);
threads.add(t);
t.start();
}
}
private void work() {
try {
while (true) {
Runnable task = tasks.take(); // sleeps while the queue is empty
if (task == STOP) return;
task.run();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
<T> FutureTask<T> submit(Callable<T> fn) throws InterruptedException {
FutureTask<T> future = new FutureTask<>(fn);
tasks.put(future);
return future;
}
void shutdown() throws InterruptedException {
for (int i = 0; i < threads.size(); i++) tasks.put(STOP); // one sentinel per worker
for (Thread t : threads) t.join();
}
int size() {
return threads.size();
}
}
static int countPrimes(int lo, int hi) {
int count = 0;
for (int n = Math.max(lo, 2); n < hi; n++) {
boolean prime = true;
for (int d = 2; d * d <= n && prime; d++) prime = n % d != 0;
if (prime) count++;
}
return count;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
// Count the primes below 13000 in seven chunks of unequal size.
int[][] chunks = {
{0, 3000}, {3000, 4000}, {4000, 6000}, {6000, 8000}, {8000, 9000}, {9000, 12000}, {12000, 13000}
};
ThreadPool pool = new ThreadPool(3, 3);
List<FutureTask<Integer>> futures = new ArrayList<>();
for (int[] c : chunks) futures.add(pool.submit(() -> countPrimes(c[0], c[1])));
// get() waits for each task, so output follows submission order, not finishing order.
int total = 0;
for (int i = 0; i < chunks.length; i++) {
int r = futures.get(i).get();
total += r;
System.out.printf("T%d: primes in [%d, %d) = %d%n", i + 1, chunks[i][0], chunks[i][1], r);
}
pool.shutdown();
System.out.printf("total primes below 13000 = %d%n", total);
System.out.printf("threads created: %d for %d tasks%n", pool.size(), chunks.length);
}
}Step through it
Running on 7 chunks of [0, 13000), costs 3, 1, 2, 2, 1, 3, 1 ticks; 3 workers; queue capacity 3
Choosing the Number of Threads
The right size depends on what the tasks spend their time doing. CPU-bound tasks keep a core busy the whole time, so more threads than cores only adds context switches: use about N_cores threads, or N_cores + 1 to cover the occasional page fault. I/O-bound tasks spend most of their time blocked on disks or the network, so extra threads keep the cores busy while others wait.
A common rule, from Brian Goetz's Java Concurrency in Practice, is threads = N_cores × U × (1 + W / C), where U is the target CPU utilization (0 to 1) and W / C is the ratio of time spent waiting to time spent computing. With 8 cores, a target of 100% and tasks that wait 90 ms for every 10 ms of CPU, the pool should have 8 × 1 × (1 + 9) = 80 threads.
| Workload | Rule of thumb | Example on 8 cores |
|---|---|---|
| CPU-bound (computation, compression) | N_cores or N_cores + 1 | 8 or 9 threads |
| I/O-bound (network calls, database) | N_cores × (1 + W / C) | W / C = 9 gives 80 threads |
| Mixed | separate pools for CPU and I/O work | 8 for compute, 64 for I/O |
- Too few threads: cores sit idle while tasks queue
- Too many threads: memory, context switches and lock contention grow
- Measure W / C under real load rather than guessing
Bounded Queues and Rejection Policies
- Block the caller – submit() waits until a slot frees up; fine for batch jobs whose producer can slow down.
- Abort – throw an exception (RejectedExecutionException) so the caller can retry or report an error.
- Caller runs – the submitting thread runs the task itself, which keeps it busy and so throttles it gently.
- Discard – silently drop the new task; only for work that is safe to lose.
- Discard oldest – drop the task at the head of the queue and retry, when the latest data matters most.
An unbounded queue never refuses a task, but under sustained overload it grows until the process runs out of memory. A bounded queue, as in the tracer, caps the backlog. When it is full, the pool must decide what to do with a new task, and that decision is its rejection policy (Java calls it the saturation policy).
Making the submitter block, as the listings do, gives natural backpressure: a producer faster than the pool is slowed to the pool's speed. Java's ThreadPoolExecutor offers four named policies instead.
- Unbounded queue plus fixed threads: never rejects, can exhaust memory
- Bounded queue: predictable memory, needs a policy for overload
- Synchronous handoff (no queue): a task must go straight to a free worker
Built-in Pools in Java, Python and C++
Most languages ship a ready-made pool, and production code should use it. The listings on this page build one by hand so the queue, the worker loop and shutdown are visible.
In Java, Executors.newFixedThreadPool(n) returns a ThreadPoolExecutor with n workers and an unbounded queue; constructing a ThreadPoolExecutor directly lets you set core and maximum sizes, the queue and the rejection policy. In Python, concurrent.futures.ThreadPoolExecutor(max_workers=n) provides submit() and futures; for CPU-bound Python code, ProcessPoolExecutor avoids the global interpreter lock. C++ has no standard pool: std::async may create a thread per call, so programs use a hand-written pool like the one below or Boost.Asio's thread_pool.
- C# / .NET – ThreadPool and Task.Run; the runtime adds threads when it detects starvation
- Node.js – libuv's worker pool, 4 threads by default, runs file system, DNS and crypto work
- Prefer the platform pool over a hand-written one in real code
- Always shut a pool down, or its threads can keep the process alive
- Name pool threads so they are recognisable in a debugger
Thread Pool Starvation, Deadlock, and Exhaustion
- Don't block inside pooled tasks – use asynchronous I/O, or a separate pool for blocking work.
- Never wait on a task in the same bounded pool – or use a work-stealing pool such as ForkJoinPool.
- Keep tasks short – split long jobs so one task cannot hold a worker for minutes.
- Monitor the queue – a queue that only grows is the first sign of starvation.
A pool's fixed size is also its main danger. Thread pool starvation happens when every worker is busy with tasks that block for a long time, such as slow network calls, so short tasks wait in the queue even though the CPU is idle. Thread pool exhaustion is the same condition seen from outside: requests time out because no thread is available to serve them.
The worst case is thread-starvation deadlock. If a task submits another task to the same pool and waits for its result, and every worker is doing the same, all of them wait for tasks that can never start, because there is no free worker to run them. The system stops with no lock held at all.
- Starvation: workers all blocked, queue growing, CPU idle
- Deadlock: tasks waiting on tasks that cannot get a worker
- Leaks: a task that never returns permanently removes a worker
Strengths and Costs
Pools are the standard way servers, databases and GUI frameworks run concurrent work. Their costs are the ones any shared, fixed-size resource has.
- Faster start – no thread is created per task, so a task starts as soon as a worker is free
- Predictable load – the thread count, and with a bounded queue the backlog, have a ceiling
- Needs tuning – the right size depends on the workload and changes with it
- Leaky state – thread-local values survive from one task to the next unless cleared
- Harder debugging – a task runs on whichever worker is free, not on a thread of its own
- See Processes and Threads for what each worker is