14#ifndef __THREADS_POOL_H_
15#define __THREADS_POOL_H_
17#include <condition_variable>
52 if (nrThreads <= 0) nrThreads = 1;
54 for (
int i = 0; i < nrThreads; ++i)
55 Threads.emplace_back(std::make_unique<JobWorkerThread>(
this));
74 std::lock_guard lock(Mutex);
76 for (
auto &worker : Threads) worker->SetStopUnlocked();
81 for (
auto &worker : Threads) worker->Join();
92 for (
auto &worker : Threads) worker->Start();
104 std::lock_guard lock(Mutex);
120 std::lock_guard lock(Mutex);
121 JobsQueue.push(std::move(job));
137 std::unique_lock lock(FinishMutex);
139 if (FinishCount >= FinishLimit)
return;
141 ConditionFinish.wait(lock, [
this] {
return FinishCount >= FinishLimit; });
143 if (FinishCount >= FinishLimit)
return;
158 if (nrThreads <= 0) nrThreads = 1;
160 size_t oldSize = Threads.size();
162 if (oldSize == nrThreads)
return;
164 if (oldSize < nrThreads) {
165 for (
size_t i = oldSize; i < nrThreads; ++i) {
166 Threads.emplace_back(std::make_unique<JobWorkerThread>(
this));
167 Threads.back()->Start();
171 std::lock_guard lock(Mutex);
172 for (
size_t i = oldSize; i < nrThreads; ++i)
173 Threads[i]->SetStopUnlocked();
178 for (
size_t i = oldSize; i < nrThreads; ++i) Threads[i]->Join();
179 Threads.resize(nrThreads);
194 std::unique_lock lock(FinishMutex);
205 inline void NotifyOne() { Condition.notify_one(); }
213 inline void NotifyAll() { Condition.notify_all(); }
221 inline bool HasWork()
const {
return !JobsQueue.empty(); }
230 void NotifyFinish() { ConditionFinish.notify_all(); }
233 std::condition_variable
236 std::mutex FinishMutex;
237 std::condition_variable ConditionFinish;
240 size_t FinishCount = 0;
242 std::numeric_limits<size_t>::max();
245 std::queue<std::shared_ptr<Job>>
248 std::vector<std::unique_ptr<JobWorkerThread>>
ThreadsPool class for holding and controlling a pool of threads.
void Start()
Start all the threads in the threads pool.
void AddRunJob(const std::shared_ptr< Job > &job)
Add a job to be executed by the threads pool.
void WaitForFinish()
Wait for all jobs to finish.
void SetFinishLimit(size_t limit)
Set the finish limit.
void AddRunJob(std::shared_ptr< Job > &&job)
Add a job to be executed by the threads pool.
void Resize(size_t nrThreads)
Resize the threads pool.
void Stop()
Stop all the threads in the threads pool.
~ThreadsPool()
Destructor.
ThreadsPool(int nrThreads=0)
Construct a new Thread pool object.
WorkerThread class for a thread in a threads pool.