Skip to content

Latest commit

History

6 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

modern-cpp-thread-pool

A lightweight, modern C++17 thread pool implementation with a focus on clarity, correctness, and practical performance evaluation. This project is designed both as a reusable library and as a learning-oriented reference for modern C++ concurrency, testing, and benchmarking practices.


Features

  • C++17 Core Library – Fully compatible with C++17; no additional dependencies required for the core thread pool.
  • Header-only Implementation – Simple to include in any project without separate compilation.
  • Configurable Thread Pool Size – Specify the number of threads explicitly, or use the default: std::thread::hardware_concurrency() * 2.
  • Task Submission with std::future – Submit tasks and retrieve results asynchronously.
  • Lifecycle Management with RAII and Manual Shutdown – Threads can be shut down manually with ShutDownMode::GRACEFUL(default) or ShutDownMode::IMMEDIATE; if not explicitly shut down, the pool performs a graceful shutdown automatically.
  • Thread-safe Task Queue – Internal task queue supports concurrent submission from multiple threads.
  • Unit Tests with GoogleTest – Comes with a complete test suite for correctness validation.
  • Optional C++20 Demo – Demonstrates usage with std::osyncstream for synchronized console output.
  • Performance Benchmarks – Built-in benchmark using Google Benchmark to measure throughput and latency.

Project Structure

.
├── include/ # contains the header-only library
├── src/ # provides example usage demonstrating the API
├── bench/ # includes performance benchmarks
├── tests/ # contains unit tests to validate correctness
└── CMakeLists.txt

Quick Start

#include"thread_pool.hpp"
#include<iostream>intmain() {
ThreadPool pool{4};
auto future = pool.submit([] { return42; });
std::cout << "Result: " << future.get() << std::endl;
return0;
}

API Overview

FunctionDescription
ThreadPool(size_t num_threads = default_thread_pool_size())Construct a thread pool with the given number of threads.
template<typename F, typename... Args> auto submit(F&& f, Args&&... args)Submit a task to the pool and get a std::future for the result.
void shutdown(ShutDownMode mode = ShutDownMode::GRACEFUL)Shut down all threads gracefully or immediately.
size_t size() constGet the number of threads in the pool.

Requirements

  • C++17 compatible compiler (for the thread pool itself)
  • C++20 compatible compiler only required for running the demo (src/main.cpp) using std::osyncstream)
    (GCC ≥ 11, Clang ≥ 14 recommended for demo)
  • CMake ≥ 3.14
  • pthread (Linux / macOS)

Optional dependencies (automatically fetched by CMake if needed):

  • GoogleTest (for unit tests)
  • Google Benchmark (for benchmark tests; optional)
    • Benchmark tests in bench/bench.cpp compare with Boost.
    • Boost is NOT required for the core thread pool; it is only needed if you want to run the benchmark comparisons with Boost.
      • On Ubuntu 24.04, Boost 1.83 can be installed via apt.
      • If the installed Boost version differs, adjust the path in bench/CMakeLists.txt line 19.

Build Instructions

Clone the repository

git clone git@github.com:TTSS0529/modern-cpp-thread-pool.git
cd modern-cpp-thread-pool

Build example & tests

mkdir build &&cd build
cmake ..
cmake --build .
./demo # Run the demo program to show basic thread pool usage
ctest -v # Run unit tests with verbose output
ctest -T memcheck # Perform memory checks to detect leaks or errors

Benchmark(run in /build/)

# Configure the project to build the benchmark in Release mode
cmake -DTHREADPOOL_BUILD_BENCHMARK=ON -DCMAKE_BUILD_TYPE=Release ..
cmake --build .# Run the benchmark with a neutral CPU personality to avoid architecture-specific optimizations
setarch $(uname -m) -R ./bench/pool_bench

This benchmark compares this ThreadPool with Boost.Asio’s thread pool. It submits a large number of CPU-bound tasks (dummy_task) in chunks, measures execution time, and evaluates performance across different thread counts, task sizes, and chunk sizes. Use it to check throughput, scalability, and optimal configuration of this thread pool.

Benchmark Results (Time in ms)

Performance Difference Formula:
[ \text{Diff (%)} = \frac{\text{MyThreadPool} - \text{BoostThreadPool}}{\text{BoostThreadPool}} \times 100 ]

Positive value → MyThreadPool is slower
Negative value → MyThreadPool is faster

ThreadsTasksTask SizeMyThreadPool (ms)BoostThreadPool (ms)Diff (%)
1100k1k842.33839.120.38
1100k10k836.84842.69-0.70
11M1k8464.968382.840.98
11M10k8436.118453.47-0.20
2100k1k422.26422.52-0.06
2100k10k415.06417.70-0.63
21M1k4209.314216.39-0.17
21M10k4222.164216.770.13
4100k1k264.42269.07-1.73
4100k10k300.37299.790.20
41M1k2640.902647.72-0.26
41M10k2662.152742.34-2.90
8100k1k221.21224.00-1.26
8100k10k256.35258.22-0.73
81M1k2233.512247.67-0.63
81M10k2253.352286.54-1.45
16100k1k189.09188.610.26
16100k10k220.12220.92-0.36
161M1k1837.091842.14-0.27
161M10k1884.031871.010.69
Summary:
  • For small tasks (100k) or small task sizes (1k–10k), MyThreadPool and BoostThreadPool perform nearly identically, with differences mostly within ±1%.
  • For large tasks (1M), differences remain small across all thread counts (1–16), typically within ±3%.
  • No scenario shows a significant performance advantage for either pool; overall, MyThreadPool and BoostThreadPool are comparable.
  • Slight variations (~3%) may occur due to scheduling and system load, but MyThreadPool is generally on par with BoostThreadPool.

License

This project is licensed under the MIT License. See the LICENSE file for details.

About

A lightweight, header-only C++17 thread pool focused on clarity, correctness, and practical performance benchmarking.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages