Skip to content

lona-cn/ThreadPoolLite

Repository files navigation

ThreadPoolLite

Language: English | 简体中文 | العربية

A modern C++23 Thread Pool implementation derived from https://github.com/progschj/ThreadPool.

Overview

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.

Features

  • C++23 Compatible: Utilizes the latest C++23 features such as std::jthread, std::move_only_function, and std::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::future objects for asynchronous result retrieval
  • Error Handling: Uses std::expected to 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

Usage

Basic Example

#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;
}

Multiple Tasks

#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;
}

Core Implementation

Thread Management

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.

Task Queue

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.

Synchronization

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.

Graceful Shutdown

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.

API Reference

ThreadPool Class

Constructors

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

Methods

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::expected containing either a std::future to 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

Destructor

~ThreadPool();
  • Description: Destroys the thread pool, automatically calling shutdown() and joining all worker threads

Requirements

  • A C++23 compliant compiler (GCC 13+, Clang 16+, MSVC 2022+)
  • Standard C++ Library with C++23 support

Build Systems

ThreadPoolLite supports multiple build systems for easy integration into various projects.

Using Makefile

The project includes a Makefile that supports macOS, Linux, and Windows platforms.

Basic Commands

# 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 help

Using CMake

The project provides CMake support for cross-platform build and integration.

Basic Usage

# 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

Integration in Your CMake Project

# Find the package
find_package(ThreadPoolLite REQUIRED)

# Link with your target
target_link_libraries(your_target ThreadPoolLite::ThreadPoolLite)

Using xmake

xmake is a lightweight build system that also supports cross-platform development.

Basic Commands

# 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 uninstall

License

This 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.

About

A modern C++23 Thread Pool implementation derived from https://github.com/progschj/ThreadPool.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published