14#ifndef __THREADS_POOL_H_
15#define __THREADS_POOL_H_
17#include <condition_variable>
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)
77 worker->SetStopUnlocked();
82 for (
auto &worker : Threads)
94 for (
auto &worker : Threads)
107 std::lock_guard lock(Mutex);
123 std::lock_guard lock(Mutex);
124 JobsQueue.push(std::move(job));
140 std::unique_lock lock(FinishMutex);
142 if (FinishCount >= FinishLimit)
145 ConditionFinish.wait(lock, [
this] {
return FinishCount >= FinishLimit; });
147 if (FinishCount >= FinishLimit)
166 size_t oldSize = Threads.size();
168 if (oldSize == nrThreads)
171 if (oldSize < nrThreads) {
172 for (
size_t i = oldSize; i < nrThreads; ++i) {
173 Threads.emplace_back(std::make_unique<JobWorkerThread>(
this));
174 Threads.back()->Start();
178 std::lock_guard lock(Mutex);
179 for (
size_t i = oldSize; i < nrThreads; ++i)
180 Threads[i]->SetStopUnlocked();
185 for (
size_t i = oldSize; i < nrThreads; ++i)
187 Threads.resize(nrThreads);
202 std::unique_lock lock(FinishMutex);
213 inline void NotifyOne() { Condition.notify_one(); }
221 inline void NotifyAll() { Condition.notify_all(); }
229 inline bool HasWork()
const {
return !JobsQueue.empty(); }
238 void NotifyFinish() { ConditionFinish.notify_all(); }
241 std::condition_variable
244 std::mutex FinishMutex;
245 std::condition_variable ConditionFinish;
248 size_t FinishCount = 0;
250 std::numeric_limits<size_t>::max();
253 std::queue<std::shared_ptr<Job>>
256 std::vector<std::unique_ptr<JobWorkerThread>>
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.