DataReelDataReelC++ Toolkit Documentation

Thread Pool

ThreadPool runs tasks on a fixed set of std::thread workers. It is the one thread class DataReel 7 keeps.

Contents

Overview
Functions

Overview

DataReel 7 removed gxThread, gxMutex, gxCondition, gxSemaphore and the old thrPool class: use std::thread or std::jthread, std::mutex, std::condition_variable and std::counting_semaphore. The standard library still has no thread pool, so thrpool.h provides datareel::ThreadPool, header only.

ThreadPool pool(8);
auto result = pool.Submit([](int a, int b) { return a + b; }, 2, 3);
std::cout << result.get() << "\n";        // 5; exceptions are rethrown by get()
pool.Wait();                              // All queued tasks finished

Functions

explicit ThreadPool::ThreadPool(std::size_t num_threads = 0)

Starts the workers; 0 means one per CPU.

ThreadPool::~ThreadPool()

Finishes every queued task, then joins the workers.

std::future<R> ThreadPool::Submit(F &&f, Args &&...args)

Queues a task. The future holds its result or exception.

void ThreadPool::Wait()

Blocks until the queue is empty and no task is running.

std::size_t ThreadPool::Size() const / Pending()

Worker count and queued task count.