Consult complete reference documentation at cool::thread_pool.
Working with multiple threads in C++ is powerful, but also complex and error-prone:
std::thread
objects is inefficient.mutex
, condition_variable
, and lifecycle management requires care.cool::thread_pool
The cool::thread_pool
class provides a lightweight and modern abstraction for concurrent task execution:
std::future
so the caller can retrieve task results later.close
, join
, and detach
.workers_
) continuously runs tasks pulled from a mutex-protected queue (tasks_
).std::function<void()>
.std::condition_variable
until a new task is available.close()
is called, no new tasks can be added.join()
waits for all worker threads to finish safely.thread_pool
and executing tasks#include <cool/thread_pool.hpp>
#include <iostream>
int main() {
const std::size_t nthreads = 4; // Number of threads in the pool
cool::thread_pool pool(nthreads);
// Enqueue asynchronous tasks
auto future1 = pool.enqueue([] { return 42; });
auto future2 = pool.enqueue([](int a, int b) { return a + b; }, 10, 5);
std::cout << "Result 1: " << future1.get() << "\n"; // 42
std::cout << "Result 2: " << future2.get() << "\n"; // 15
pool.join(); // Waits for all threads to finish
}
close
, join
, detach
cool::thread_pool pool;
auto f = pool.enqueue([] { return 1 + 2; });
std::cout << f.get() << "\n"; // 3
pool.close(); // No new tasks allowed
// pool.enqueue([] { return 9; }); // Throws exception!
pool.join(); // Waits for threads to terminate
nthreads
is not specified, it defaults to std::thread::hardware_concurrency()
.std::packaged_task
to wrap arbitrary function calls.std::result_of
/ std::invoke_result
.Use cool::thread_pool
when you:
std::thread
.std::future
for retrieving results.std::async
or std::jthread
.cool::thread_pool
offers an elegant and practical way to leverage parallel execution in C++, with minimal boilerplate and maximum safety.