Language: English | 简体中文 | العربية
A modern C++23 Thread Pool implementation derived from https://github.com/progschj/ThreadPool.
ThreadPoolLite is a lightweight and efficient thread pool implementation written in C++23. It provides a simple interface to manage a pool of worker threads that can execute tasks asynchronously. This implementation leverages modern C++ features for improved performance, safety, and usability.
- C++23 Compatible: Utilizes the latest C++23 features such as
std::jthread,std::move_only_function, andstd::expected - Automatic Resource Management: Worker threads are automatically joined upon destruction using
std::jthread - Type-Safe Task Submission: Supports any callable object with perfect forwarding and type deduction
- Future-Based Result Retrieval: Tasks return
std::futureobjects for asynchronous result retrieval - Error Handling: Uses
std::expectedto properly handle errors during task submission - Graceful Shutdown: Supports proper thread pool shutdown with task completion
- Thread Safety: All operations are thread-safe with proper synchronization
#include "ThreadPool.hpp"
#include <iostream>
int main() {
// Create a thread pool with 4 worker threads
ThreadPool pool(4);
// Submit a task and get a future
auto result = pool.enqueue([](int value) { return value * 2; }, 42);
// Wait for the result and print it
if (result) {
std::cout << "Result: " << result->get() << std::endl; // Output: Result: 84
} else {
std::cerr << "Error: " << result.error() << std::endl;
}
return 0;
}#include "ThreadPool.hpp"
#include <vector>
#include <future>
int main() {
ThreadPool pool(8); // Create a pool with 8 threads
std::vector<std::future<int>> results;
// Submit multiple tasks
for (int i = 0; i < 10; ++i) {
auto result = pool.enqueue([i]() {
// Simulate some work
std::this_thread::sleep_for(std::chrono::seconds(1));
return i * i;
});
if (result) {
results.push_back(std::move(*result));
}
}
// Collect results
for (auto& result : results) {
std::cout << "Result: " << result.get() << std::endl;
}
return 0;
}The thread pool manages a collection of worker threads (std::jthread) that continuously wait for tasks to execute. When a task is submitted, it's added to a queue, and one of the worker threads picks it up for execution.
Tasks are stored in a queue of std::move_only_function<void()>, which allows efficient storage of any callable object that can be moved but not copied.
The implementation uses a mutex (std::mutex) and a condition variable (std::condition_variable_any) to ensure thread-safe access to the task queue and to notify worker threads when new tasks are available.
When the thread pool is shut down or destroyed, it notifies all worker threads and waits for them to complete their current tasks before exiting.
explicit ThreadPool(std::size_t thread_count = std::jthread::hardware_concurrency());- Parameters:
thread_count- The number of worker threads to create (defaults to the number of hardware threads) - Description: Creates a new thread pool with the specified number of worker threads
template <typename F, typename... Args>
auto enqueue(F&& f, Args&&... args) -> std::expected<std::future<std::invoke_result_t<F, Args...>>, std::string>;- Parameters:
f- The callable object to execute,args- Arguments to pass to the callable object - Return Value: A
std::expectedcontaining either astd::futureto the result of the task or an error message - Description: Submits a task to the thread pool for execution
void shutdown();- Description: Initiates the shutdown of the thread pool, stopping the acceptance of new tasks and notifying all worker threads
~ThreadPool();- Description: Destroys the thread pool, automatically calling
shutdown()and joining all worker threads
- A C++23 compliant compiler (GCC 13+, Clang 16+, MSVC 2022+)
- Standard C++ Library with C++23 support
ThreadPoolLite supports multiple build systems for easy integration into various projects.
The project includes a Makefile that supports macOS, Linux, and Windows platforms.
# Build the example
make
# Install the library (default: /usr/local/include/ThreadPoolLite)
make install
# Install to a custom location
make install PREFIX=/path/to/custom/location
# Uninstall
make uninstall
# Clean build files
make clean
# Show help information
make helpThe project provides CMake support for cross-platform build and integration.
# Create and enter build directory
mkdir build && cd build
# Configure (with optional example)
cmake .. -DBUILD_EXAMPLE=ON
# Build
cmake --build .
# Install (default: system include directory)
cmake --install .
# Install to a custom location
cmake --install . --prefix /path/to/custom/location# Find the package
find_package(ThreadPoolLite REQUIRED)
# Link with your target
target_link_libraries(your_target ThreadPoolLite::ThreadPoolLite)xmake is a lightweight build system that also supports cross-platform development.
# Build the library
xmake
# Build the example
xmake build example
# Install the library (default: /usr/local/include/ThreadPoolLite)
xmake install
# Install to a custom location
xmake install -o /path/to/custom/location
# Uninstall
xmake uninstallThis project is derived from https://github.com/progschj/ThreadPool and is licensed under the MIT License. For more details, please refer to the LICENSE file in the project root.