ThreadPool is a modern, header-only C++ threadpool library.
Requires C++17 or later and thread support. Build and run the example with:
g++ -std=c++17 -pthread example.cpp -o example.out
./example.out#include "threadpool.hpp"
#include <iostream>
#include <memory>
#include <mutex>
#include <vector>
int main() {
tp::ThreadPool threadpool; // Create a threadpool
std::mutex mutex;
std::vector<std::shared_ptr<tp::Task>> tasks; // Vector to store threadpool tasks
for (unsigned int i = 0; i < 10; ++i) {
tasks.push_back(threadpool.schedule([i, &mutex]() {
std::lock_guard<std::mutex> lock(mutex);
std::cout << "Printing from task: " << i << std::endl;
})); // Schedule tasks and add them to the vector
}
for (const auto& task : tasks) { // Wait on every task
task->wait();
}
std::cout << "All tasks done!" << std::endl;
return 0;
}schedule(callable, launch_if_busy = false)accepts a zero-argument callable, including move-only lambdas. Capture arguments in the callable instead of passing avoid*argument.Task::wait()waits for task completion.wait_for(duration)andwait_until(time_point)returnTASK_STATUS_RUNNINGif the task has not completed before the timeout.get_status()reads the task status safely. Failed tasks retain their exception throughget_exception_ptr(), which can be passed tostd::rethrow_exception.TaskManager::insert(task)tracks a task;wait()and the manager's destructor wait for tracked tasks to finish.ThreadPool::size()reports the requested worker count.resize(size)requests a new count; shrinking returns before all excess workers have exited.- Setting
launch_if_busytotrueallows a task to run on a separate detached thread when pool capacity is occupied. Wait for these tasks explicitly or track them with aTaskManager.