cool

cool::thread_pool - A Simple and Intuitive Thread Pool Implementation

Consult complete reference documentation at cool::thread_pool.

Motivation

Working with multiple threads in C++ is powerful, but also complex and error-prone:

The Problem: How can we manage concurrent tasks safely and efficiently?


Solution: cool::thread_pool

The cool::thread_pool class provides a lightweight and modern abstraction for concurrent task execution:


How it Works

Internal Structure:


Usage Example

1. Creating a thread_pool and executing tasks

#include <cool/thread_pool.hpp>
#include <iostream>

int main() {
  const std::size_t nthreads = 4; // Number of threads in the pool
  cool::thread_pool pool(nthreads);

  // Enqueue asynchronous tasks
  auto future1 = pool.enqueue([] { return 42; });
  auto future2 = pool.enqueue([](int a, int b) { return a + b; }, 10, 5);

  std::cout << "Result 1: " << future1.get() << "\n"; // 42
  std::cout << "Result 2: " << future2.get() << "\n"; // 15

  pool.join(); // Waits for all threads to finish
}

2. Explicit control with close, join, detach

cool::thread_pool pool;

auto f = pool.enqueue([] { return 1 + 2; });
std::cout << f.get() << "\n"; // 3

pool.close(); // No new tasks allowed
// pool.enqueue([] { return 9; }); // Throws exception!

pool.join(); // Waits for threads to terminate

Additional Features


When to Use

Use cool::thread_pool when you:


When Not to Use


Conclusion

cool::thread_pool offers an elegant and practical way to leverage parallel execution in C++, with minimal boilerplate and maximum safety.