|
TEC
A lightweight C++ library enabling safe, efficient execution in multithreaded and concurrent systems.
|
Simple, non-stealing thread pool implementation using a single shared task queue. More...
#include <tec_thread_pool.hpp>
Public Types | |
| using | TaskFunc = std::function< void()> |
| Type alias for the task function objects stored and executed by the pool. | |
Public Member Functions | |
| ThreadPool (size_t num_threads) | |
| Constructs a thread pool with the specified number of worker threads. | |
| constexpr size_t | get_num_threads () |
| Returns the number of worker threads in this pool. | |
| virtual | ~ThreadPool () |
| Destructor – gracefully shuts down the thread pool. | |
| template<class F > | |
| void | enqueue (F &&task) |
| Enqueues a new task to be executed by one of the worker threads. | |
Protected Attributes | |
| size_t | num_threads_ |
| Number of worker threads in the pool (set during construction) | |
| std::vector< std::thread > | workers_ |
| Container holding all worker std::thread objects. | |
| std::queue< TaskFunc > | tasks_ |
| Thread-safe queue of pending tasks (protected by queue_mutex_) | |
| std::mutex | queue_mutex_ |
| Mutex protecting access to the tasks_ queue. | |
| std::condition_variable | condition_ |
| Condition variable used to wake up sleeping worker threads when tasks arrive. | |
| std::atomic< bool > | stop_ |
| Atomic flag used to signal all worker threads to terminate. | |
Simple, non-stealing thread pool implementation using a single shared task queue.
Classic worker thread pattern with condition variable notification. Tasks are std::function<void()> objects (can wrap lambdas, functors, bound functions, etc.).
Thread safety: all public methods are thread-safe. Destruction: waits for all currently running tasks to finish (but does not wait for tasks that are still in the queue when stop is requested).
|
inlineexplicit |
Constructs a thread pool with the specified number of worker threads.
| num_threads | Desired number of worker threads (usually std::thread::hardware_concurrency() or similar) |
Starts exactly num_threads worker threads that immediately begin waiting for tasks via condition variable.
|
inlinevirtual |
Destructor – gracefully shuts down the thread pool.
Sets the stop flag, wakes up all waiting threads, and joins every worker thread.
Important:
Enqueues a new task to be executed by one of the worker threads.
| F | Type of the callable (usually deduced) |
| task | Callable object (lambda, std::bind result, function pointer + arguments, etc.) |
The task is moved into the internal queue (zero-copy when possible). Notification is sent to exactly one waiting worker (if any).
Thread-safe — can be called from any thread, including worker threads.
Returns the number of worker threads in this pool.