C++ · Module 19 · Lesson 71 min read

Project: Multithreaded Task Scheduler

What a thread pool does

Creating a thread per task is expensive. A thread pool starts N worker threads once; tasks are pushed onto a queue; idle workers take the next task. Results come back through futures.

Features checklist

  1. ThreadPool(n) starts n std::jthread workers
  2. submit(f, args...) returns std::future<R> for the task's result
  3. Thread-safe task queue (std::mutex + std::condition_variable)
  4. Graceful shutdown: finish queued tasks, then stop workers (destructor)
  5. Exceptions thrown by tasks reach the caller via future.get()
  6. Statistics: tasks completed (std::atomic)

Design

arduino
class ThreadPool {
    std::vector<std::jthread> workers_;
    std::queue<std::function<void()>> tasks_;
    std::mutex m_;
    std::condition_variable cv_;
    bool stopping_ = false;
public:
    template <typename F, typename... Args>
    auto submit(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>>;
};

submit wraps the call in a std::packaged_task (which owns a promise), stores a small lambda that runs it in the queue, and returns the task's future.

Concepts practised

Variadic templates & perfect forwarding, std::invoke_result_t, std::packaged_task and futures, std::shared_ptr (packaged_task is move-only, std::function needs copyable), mutex/condition variable, std::jthread, RAII shutdown, std::atomic.

Pitfalls ⚠️

  • Never hold the lock while running a task (other workers would block)
  • Workers must wake up on shutdown (notify_all)
  • Output from tasks interleaves — collect results and print from the main thread

Extensions

Task priorities (std::priority_queue), delayed/scheduled tasks with <chrono>, cancellation with std::stop_token, work stealing, wait_all().

Example

C++
#include <atomic>
#include <condition_variable>
#include <functional>
#include <future>
#include <iostream>
#include <memory>
#include <mutex>
#include <numeric>
#include <queue>
#include <stdexcept>
#include <string>
#include <thread>
#include <type_traits>
#include <vector>

class ThreadPool {
public:
    explicit ThreadPool(std::size_t n) {
        for (std::size_t i = 0; i < n; ++i)
            workers_.emplace_back([this] { work(); });
    }
    ~ThreadPool() {
        { std::lock_guard lock(m_); stopping_ = true; }
        cv_.notify_all();                               // wake everyone; jthreads join automatically
    }
    ThreadPool(const ThreadPool&) = delete;
    ThreadPool& operator=(const ThreadPool&) = delete;

    template <typename F, typename... Args>
    auto submit(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>> {
        using R = std::invoke_result_t<F, Args...>;
        auto task = std::make_shared<std::packaged_task<R()>>(
            [f = std::forward<F>(f), ... args = std::forward<Args>(args)]() mutable { return f(args...); });
        std::future<R> result = task->get_future();
        {
            std::lock_guard lock(m_);
            if (stopping_) throw std::runtime_error("pool is stopping");
            tasks_.push([task] { (*task)(); });
        }
        cv_.notify_one();
        return result;
    }
    int completed() const { return completed_; }

private:
    void work() {
        while (true) {
            std::function<void()> job;
            {
                std::unique_lock lock(m_);
                cv_.wait(lock, [this] { return stopping_ || !tasks_.empty(); });
                if (stopping_ && tasks_.empty()) return;  // finish queued work, then exit
                job = std::move(tasks_.front());
                tasks_.pop();
            }
            job();                                       // run WITHOUT holding the lock
            ++completed_;
        }
    }
    std::mutex m_;
    std::condition_variable cv_;
    std::queue<std::function<void()>> tasks_;
    bool stopping_ = false;
    std::atomic<int> completed_{ 0 };
    std::vector<std::jthread> workers_;                  // declared last: joined first on destruction
};

long long sum_range(long long from, long long to) {
    long long s = 0;
    for (long long i = from; i <= to; ++i) s += i;
    return s;
}

double monthly_report(int month) {
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
    if (month == 13) throw std::invalid_argument("no month 13");
    return month * 1000.0;
}

int main() {
    std::vector<std::future<long long>> parts;
    {
        ThreadPool pool(4);
        const long long N = 10'000'000, chunk = N / 8;
        for (long long i = 0; i < 8; ++i)
            parts.push_back(pool.submit(sum_range, i * chunk + 1, (i + 1) * chunk));

        long long total = 0;
        for (auto& f : parts) total += f.get();
        std::cout << "sum 1..10,000,000 = " << total << " (formula " << N * (N + 1) / 2 << ")\n";

        std::vector<std::future<double>> reports;
        for (int m : { 1, 2, 13, 4 }) reports.push_back(pool.submit(monthly_report, m));
        for (std::size_t i = 0; i < reports.size(); ++i) {
            try {
                double value = reports[i].get();          // may throw: get the value before printing
                std::cout << "report " << i << ": " << value << '\n';
            } catch (const std::exception& e) {
                std::cout << "report " << i << " failed: " << e.what() << '\n';
            }
        }

        auto greeting = pool.submit([](std::string name) { return "Namaste, " + name + "!"; }, std::string("Asha"));
        std::cout << greeting.get() << '\n';

        for (int i = 0; i < 20; ++i) pool.submit([] { std::this_thread::sleep_for(std::chrono::milliseconds(1)); });
        std::cout << "submitted 20 more tasks; destructor will finish them before stopping\n";
    }                                                      // pool shuts down gracefully here
    std::cout << "pool stopped cleanly\n";
    return 0;
}

/* Output:
sum 1..10,000,000 = 50000005000000 (formula 50000005000000)
report 0: 1000
report 1: 2000
report 2 failed: no month 13
report 3: 4000
Namaste, Asha!
submitted 20 more tasks; destructor will finish them before stopping
pool stopped cleanly
*/