Skip to content

mq1n/ThreadPool-cpp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ThreadPool-cpp

A fast C++ thread pool with work-stealing and priority scheduling.

Features

  • Work-stealing for automatic load balancing
  • Priority-based task scheduling (0-255)
  • Future-based API with return values
  • Thread affinity support
  • Exception safe
  • Zero dependencies (only standard C++)

Requirements

  • C++17 or later
  • CMake 3.14+ (optional)

Quick Start

# Build with CMake
mkdir build && cd build
cmake .. && make

# Or just copy these files to your project:
# - include/ThreadPool.hpp
# - src/ThreadPool.cpp

Usage

#include "ThreadPool.hpp"

// Basic usage
ThreadPool pool(4);  // 4 threads
auto future = pool.Submit([]() { return 42; });
std::cout << future.get() << std::endl;  // prints 42

// With priorities (0-255, higher = more urgent)
auto urgent = pool.SubmitPriority(200, []() { return "urgent"; });
auto normal = pool.Submit([]() { return "normal"; });  // default: 128

// With arguments
auto sum = pool.Submit([](int a, int b) { return a + b; }, 10, 20);
std::cout << sum.get() << std::endl;  // prints 30

// Batch processing
std::vector<std::future<int>> futures;
for (int i = 0; i < 10; ++i) {
    futures.push_back(pool.Submit([i]() { return i * i; }));
}

API

// Constructor
ThreadPool(size_t numThreads = 0,      // 0 = auto-detect
           size_t maxQueueSize = 10000, // per-thread limit
           bool enableAffinity = false) // CPU pinning

// Submit task
auto Submit(F&& func, Args&&... args) -> future<result>

// Submit with priority
auto SubmitPriority(uint8_t priority, F&& func, Args&&... args) -> future<result>

// Utilities
size_t GetThreadCount()
size_t GetPendingTaskCount()
bool WaitForCompletion(uint32_t timeoutMs = 0)
void Shutdown(bool graceful = true)

License

MIT License - see LICENSE file for details.

About

A fast C++ thread pool with work-stealing and priority scheduling

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published