Player12
An open source football management simulator
Loading...
Searching...
No Matches
ThreadPool Class Reference

Small fixed-size pool of background workers for batch work. More...

#include <thread_pool.h>

Public Member Functions

 ThreadPool (unsigned worker_count)
 
 ~ThreadPool ()
 
 ThreadPool (const ThreadPool &)=delete
 
ThreadPool & operator= (const ThreadPool &)=delete
 
unsigned getWorkerCount () const
 
void parallelFor (std::size_t count, const std::function< void(std::size_t)> &task)
 

Static Public Member Functions

static unsigned defaultThreadCount ()
 

Static Public Attributes

static constexpr unsigned MAX_THREADS = 8
 

Private Member Functions

void workerLoop (const std::stop_token &stop)
 

Private Attributes

std::mutex mutex
 
std::condition_variable_any wake
 
std::deque< std::function< void()> > jobs
 
std::vector< std::jthread > workers
 

Detailed Description

Small fixed-size pool of background workers for batch work.

Workers run below the priority of the calling thread so background simulation never competes with the UI or other applications. parallelFor() lets the calling thread take part in its own batch, so it completes even when every worker is busy and cannot deadlock when called from a worker.

Constructor & Destructor Documentation

◆ ThreadPool() [1/2]

ThreadPool::ThreadPool ( unsigned  worker_count)
explicit

◆ ~ThreadPool()

ThreadPool::~ThreadPool ( )

Stops every worker, then joins them; queued helper jobs are dropped.

◆ ThreadPool() [2/2]

ThreadPool::ThreadPool ( const ThreadPool &  )
delete

Member Function Documentation

◆ defaultThreadCount()

unsigned ThreadPool::defaultThreadCount ( )
static

Threads a batch should use including the caller: FM_SIM_THREADS when set (1 = run on the caller only), otherwise one less than the hardware threads so the UI thread keeps a core; always in [1, MAX_THREADS].

◆ getWorkerCount()

unsigned ThreadPool::getWorkerCount ( ) const
inline

◆ operator=()

ThreadPool & ThreadPool::operator= ( const ThreadPool &  )
delete

◆ parallelFor()

void ThreadPool::parallelFor ( std::size_t  count,
const std::function< void(std::size_t)> &  task 
)

Runs task(i) for every i in [0, count) on the workers and the calling thread, returning once all calls finished. The first exception thrown by a task is rethrown here after the batch completed.

◆ workerLoop()

void ThreadPool::workerLoop ( const std::stop_token &  stop)
private

Member Data Documentation

◆ jobs

std::deque<std::function<void()> > ThreadPool::jobs
private

◆ MAX_THREADS

constexpr unsigned ThreadPool::MAX_THREADS = 8
staticconstexpr

Cap on the threads of a batch and on a pool's workers.

◆ mutex

std::mutex ThreadPool::mutex
private

◆ wake

std::condition_variable_any ThreadPool::wake
private

◆ workers

std::vector<std::jthread> ThreadPool::workers
private

The documentation for this class was generated from the following files: