AlgoViz

Thread pool

medium 70 min

A few threads that live long, one queue with a limit, and a loop: take, run, repeat.

Watch lesson5:06

A thread pool from nothing

Read it, run it, change a line and run it again.

Loading editor…

Try `limit=2` and a task that sleeps, and watch the refusals.

The same in Java
import java.util.*;import java.util.concurrent.*;/** The pool did not take the job. Nothing was started. */class Rejected extends RuntimeException {    Rejected(String why) { super(why); }}/** FutureTask runs the code once and keeps its value or its exception. */class Job<T> extends FutureTask<T> {    Job(Callable<T> code) { super(code); }}class TaskPool {    private final Deque<Job<?>> jobs = new ArrayDeque<>();  // guarded by this    private final List<Thread> threads = new ArrayList<>();    private final int limit;    private boolean closed = false;                         // guarded by this    TaskPool(int workers, int limit) {        if (workers < 1 || limit < 1)            throw new IllegalArgumentException("at least one worker and one place in the queue");        this.limit = limit;        for (int i = 0; i < workers; i++) threads.add(new Thread(this::work, "worker-" + i));        for (Thread t : threads) t.start();    }    private void work() {        while (true) {            Job<?> job;            synchronized (this) {                while (jobs.isEmpty() && !closed) {                    try {                        wait();                    } catch (InterruptedException e) {                        // only shutdownNow interrupts us; the loop looks again                    }                }                if (jobs.isEmpty()) return;    // closed, and nothing is left                job = jobs.pollFirst();            }            job.run();                         // the lock is open again        }    }    <T> Future<T> submit(Callable<T> code) {        Job<T> job = new Job<>(code);        synchronized (this) {            if (closed) throw new Rejected("the pool is closed");            if (jobs.size() >= limit) throw new Rejected("the queue is full");            jobs.addLast(job);            notify();        }        return job;    }    void shutdown() throws InterruptedException {        synchronized (this) {            closed = true;            notifyAll();        }        for (Thread t : threads) t.join();    }    int shutdownNow() {        List<Job<?>> left;        synchronized (this) {            closed = true;            left = new ArrayList<>(jobs);            jobs.clear();            notifyAll();        }        left.forEach(j -> j.cancel(false));        threads.forEach(Thread::interrupt);    // asks running jobs to stop        return left.size();    }}
The same in C++
#include <condition_variable>#include <deque>#include <functional>#include <future>#include <memory>#include <mutex>#include <stdexcept>#include <thread>#include <vector>/** The pool did not take the job. Nothing was started. */struct Rejected : std::runtime_error { using std::runtime_error::runtime_error; };using Job = std::function<void()>;   // wraps a packaged_task, so it never throwsclass TaskPool {    std::mutex gate_;                // guards jobs_ and closed_    std::condition_variable changed_;    std::deque<Job> jobs_;    const std::size_t limit_;    bool closed_ = false;    std::vector<std::thread> threads_;public:    TaskPool(int workers, std::size_t limit) : limit_(limit) {        if (workers < 1 || limit < 1)            throw std::invalid_argument("at least one worker and one place in the queue");        for (int i = 0; i < workers; ++i) threads_.emplace_back([this] { work(); });    }    ~TaskPool() { shutdown(); }      // a joinable thread must not be destroyedprivate:    void work() {        while (true) {            Job job;            {                std::unique_lock<std::mutex> hold(gate_);                changed_.wait(hold, [this] { return !jobs_.empty() || closed_; });                if (jobs_.empty()) return;   // closed, and nothing is left                job = std::move(jobs_.front());                jobs_.pop_front();            }            job();                           // the lock is open again        }    }public:    template <class F>    auto submit(F code) -> std::future<decltype(code())> {        auto task = std::make_shared<std::packaged_task<decltype(code())()>>(std::move(code));        auto result = task->get_future();        {            std::lock_guard<std::mutex> hold(gate_);            if (closed_) throw Rejected("the pool is closed");            if (jobs_.size() >= limit_) throw Rejected("the queue is full");            jobs_.emplace_back([task] { (*task)(); });        }        changed_.notify_one();        return result;    }    void shutdown() {                        // call it from one thread, not from a job        {            std::lock_guard<std::mutex> hold(gate_);            closed_ = true;        }        changed_.notify_all();        for (auto& t : threads_) if (t.joinable()) t.join();    }    std::size_t shutdown_now() {        std::deque<Job> left;        {            std::lock_guard<std::mutex> hold(gate_);            closed_ = true;            left.swap(jobs_);        }        changed_.notify_all();        return left.size();                  // their futures report broken_promise    }};
The same in TypeScript
/** The pool did not take the job. Nothing was started. */class Rejected extends Error {}/** One JavaScript thread, so "workers" are loops that await. They limit how many jobs are in flight. */interface Job {  run(): Promise<void>;  cancel(): void;}class TaskPool {  private jobs: Job[] = [];  private sleeping: (() => void)[] = [];  private closed = false;  private readonly loops: Promise<void>[];  constructor(workers: number, private readonly limit: number) {    if (workers < 1 || limit < 1) throw new Error("at least one worker and one place in the queue");    this.loops = Array.from({ length: workers }, () => this.work());  }  private async work(): Promise<void> {    while (true) {      while (this.jobs.length === 0 && !this.closed)        await new Promise<void>((wake) => this.sleeping.push(wake));      const job = this.jobs.shift();      if (!job) return; // closed, and nothing is left      await job.run();    }  }  submit<T>(code: () => Promise<T> | T): Promise<T> {    if (this.closed) return Promise.reject(new Rejected("the pool is closed"));    if (this.jobs.length >= this.limit) return Promise.reject(new Rejected("the queue is full"));    return new Promise<T>((resolve, reject) => {      const run = async () => {        try { resolve(await code()); } catch (e) { reject(e); }      };      this.jobs.push({ run, cancel: () => reject(new Rejected("cancelled before it started")) });      this.sleeping.shift()?.();    });  }  async shutdown(): Promise<void> {    this.closed = true;    this.sleeping.splice(0).forEach((wake) => wake());    await Promise.all(this.loops);  }  shutdownNow(): number {    const left = this.jobs.splice(0);    left.forEach((job) => job.cancel());    void this.shutdown();    return left.length;  }}