Player12
An open source football management simulator
Loading...
Searching...
No Matches
thread_pool.h
Go to the documentation of this file.
1// -----------------------------------------------------------------------------
2// Football Management Project
3// Copyright (c) 2025 - 2026 Flavio Milinanni. All Rights Reserved.
4//
5// This file is part of the Football Management Project.
6// See the LICENSE file in the project root.
7// -----------------------------------------------------------------------------
8
9#pragma once
10
11#include <condition_variable>
12#include <cstddef>
13#include <deque>
14#include <functional>
15#include <mutex>
16#include <stop_token>
17#include <thread>
18#include <vector>
19
30{
31 public:
33 static constexpr unsigned MAX_THREADS = 8;
34
35 explicit ThreadPool(unsigned worker_count);
38
39 ThreadPool(const ThreadPool&) = delete;
40 ThreadPool& operator=(const ThreadPool&) = delete;
41
42 unsigned getWorkerCount() const
43 {
44 return static_cast<unsigned>(workers.size());
45 }
46
52 void parallelFor(std::size_t count,
53 const std::function<void(std::size_t)>& task);
54
60 static unsigned defaultThreadCount();
61
62 private:
63 void workerLoop(const std::stop_token& stop);
64
65 std::mutex mutex;
66 std::condition_variable_any wake;
67 std::deque<std::function<void()>> jobs;
68 // Last member: workers stop and join before the queue is destroyed.
69 std::vector<std::jthread> workers;
70};
Small fixed-size pool of background workers for batch work.
Definition thread_pool.h:30
void parallelFor(std::size_t count, const std::function< void(std::size_t)> &task)
Definition thread_pool.cpp:125
static unsigned defaultThreadCount()
Definition thread_pool.cpp:148
~ThreadPool()
Definition thread_pool.cpp:99
std::deque< std::function< void()> > jobs
Definition thread_pool.h:67
static constexpr unsigned MAX_THREADS
Definition thread_pool.h:33
unsigned getWorkerCount() const
Definition thread_pool.h:42
std::condition_variable_any wake
Definition thread_pool.h:66
void workerLoop(const std::stop_token &stop)
Definition thread_pool.cpp:109
ThreadPool(const ThreadPool &)=delete
std::mutex mutex
Definition thread_pool.h:65
std::vector< std::jthread > workers
Definition thread_pool.h:69
ThreadPool & operator=(const ThreadPool &)=delete