48 lines
include/task_pool.h
Declares TaskPool, kMaxWorkers, and the submit/shutdown contracts.
// TaskPool: fixed-size worker pool with graceful shutdown.
#pragma once
#include <condition_variable>
#include <functional>
#include <mutex>
#include <queue>
#include <stdexcept>
#include <thread>
#include <vector>
 
// Hard upper bound on worker thread count.
static constexpr size_t kMaxWorkers = 32;
 
// Runs submitted tasks on a fixed pool of worker threads.
// Thread-safe: submit() and shutdown() may be called from any thread.
class TaskPool {
public:
  // Constructs the pool and starts nThreads worker threads.
  // Parameters:
  //   nThreads - number of workers; must be at least 1 and at most kMaxWorkers
  // Returns: new TaskPool; throws std::invalid_argument if nThreads is 0
  explicit TaskPool(size_t nThreads);
 
  // Destructor: calls shutdown() if not already done, then joins all workers.
  ~TaskPool();
 
  // Enqueues a task for execution by a worker thread.
  // Parameters:
  //   task - callable to execute
  // Returns: void; the task will run before any task submitted later
  void submit(std::function<void()> task);
 
  // Signals workers to drain pending tasks and exit.
  // Parameters: none
  // Returns: void; workers finish pending tasks before the destructor joins them
  void shutdown();
 
private:
  // Parameters: none
  // Returns: void; loops until shutdown_ and queue is empty
  void workerLoop();
 
  std::vector<std::thread>          workers_;   // one thread per pool worker
  std::queue<std::function<void()>> queue_;
  std::mutex                        mutex_;     // guards queue_ and shutdown_
  std::condition_variable           cv_;        // wakes workers when tasks arrive or shutdown
  bool                              shutdown_ = false; // set by shutdown() to signal exit
};