Fixed-size thread pool for running arbitrary tasks concurrently.
The thread pool maintains a set of worker threads that consume and execute tasks submitted through Submit(). Once started, tasks can be queued and processed asynchronously until Stop() is called.
Thread-safety and lifecycle
- Start() and Stop() must be called from a controller (non-worker) thread. Calling Stop() from a worker thread will deadlock, as it waits for all workers to join, including the current one.
- Submit() can be called from any thread, including workers. It safely enqueues new work for execution as long as the pool has active workers.
- Interrupt() stops new task submission and lets queued ones drain in the background. Callers can continue other shutdown steps and call Stop() at the end to ensure no remaining tasks are left to execute.
- Stop() prevents further task submission and blocks until all the queued ones are completed.
Definition at line 47 of file threadpool.h.
| void ThreadPool::Interrupt |
( |
| ) |
|
|
inline |
Stop accepting new tasks and begin asynchronous shutdown.
Wakes all worker threads so they can drain the queue and exit. Unlike Stop(), this function does not wait for threads to finish.
Note: The next step in the pool lifecycle is calling Stop(), which releases any dangling resources and resets the pool state for shutdown or restart.
Definition at line 268 of file threadpool.h.
| void ThreadPool::Stop |
( |
| ) |
|
|
inline |
Stop all worker threads and wait for them to exit.
Sets the interrupt flag, wakes all waiting workers, and joins them. Any remaining tasks in the queue will be processed before returning.
Must be called from a controller (non-worker) thread. Concurrent calls to Start() will be rejected while Stop() is in progress.
Definition at line 128 of file threadpool.h.
template<std::ranges::sized_range R>
requires (!std::is_lvalue_reference_v<R>)
Enqueues a range of tasks for asynchronous execution.
- Parameters
-
| fns | Callables to execute asynchronously. |
- Returns
- On success, a vector of futures containing each element of fns's result in order. On failure, an error indicating why the range was rejected:
This is more efficient when submitting many tasks at once, since the queue lock is only taken once internally and all worker threads are notified. For single tasks, Submit() is preferred since only one worker thread is notified.
Thread-safe: Can be called from any thread, including within submitted callables.
- Warning
- Ignoring the returned futures requires guarding tasks against uncaught exceptions, as they would otherwise be silently discarded.
Definition at line 220 of file threadpool.h.