ThreadPool class
#include <ThreadPool.h>
Thread pool for parallel task execution.
This class implements a thread pool that manages a fixed number of worker threads. Tasks can be submitted to the pool and are executed asynchronously by available worker threads.
The thread pool uses a work-stealing queue pattern where worker threads wait for tasks and execute them as they become available. The pool automatically manages thread lifecycle and task queue synchronization.
Constructors, destructors, conversion operators
- ThreadPool(size_t)
- Construct a new thread pool.
- ~ThreadPool()
- Destroy the thread pool.
Public functions
-
template<class F, class... Args>auto enqueue(F&& f, Args && ... args) >::type > -> auto
- Enqueue a task for execution.
Function documentation
ThreadPool:: ThreadPool(size_t)
Construct a new thread pool.
Creates a thread pool with the specified number of worker threads. Each worker thread is immediately started and waits for tasks to execute.
Creates worker threads that wait for tasks to be enqueued. Each worker runs in an infinite loop, waiting on a condition variable for tasks to become available.
ThreadPool:: ~ThreadPool()
Destroy the thread pool.
Destroy the thread pool and join all worker threads.
The destructor signals all worker threads to stop, waits for them to complete their current tasks, and then joins all threads.
Signals all worker threads to stop by setting the stop flag and waking all threads. Then waits for each thread to finish by calling join() on each worker thread.
template<class F, class... Args>
auto ThreadPool:: enqueue(F&& f,
Args && ... args) >::type >
Enqueue a task for execution.
| Template parameters | |
|---|---|
| F | Type of the callable object |
| Args | Types of the arguments |
| Parameters | |
| f in | The callable object to execute |
| args in | Arguments to pass to the callable |
| Returns | std::future<typename std::result_of<F(Args...)>::type> A future containing the result of the task |
| Exceptions | |
| std::runtime_error | if enqueue is called after the pool has been stopped |
Enqueue a task for asynchronous execution.
This method adds a task to the thread pool's queue. The task will be executed by an available worker thread. The method returns a future that can be used to retrieve the result or wait for completion.
Wraps the callable and its arguments into a packaged_task and adds it to the task queue. A future is returned that will contain the result when the task completes.