Maestro 0.1.0
Unified interface for quantum circuit simulation
Loading...
Searching...
No Matches
WorkerThread.h
Go to the documentation of this file.
1
11
12#pragma once
13
14#ifndef __WORKER_THREAD_H_
15#define __WORKER_THREAD_H_
16
17#include <atomic>
18#include <mutex>
19#include <thread>
20
21namespace Utils {
22
33template <class ThreadsPool, class Job> class WorkerThread {
34public:
43 explicit WorkerThread(ThreadsPool *threadsPool)
44 : threadsPool(threadsPool), StopFlag(false) {
45 Thread = std::thread(&WorkerThread::Run, this);
46 }
47
55
61 void Start() {
62 if (Thread.joinable())
63 return;
64
65 {
66 std::lock_guard lock(threadsPool->Mutex);
67 StopFlag = false;
68 }
69 Thread = std::thread(&WorkerThread::Run, this);
70 }
71
77 void Stop() {
78 if (!Thread.joinable())
79 return;
80
81 {
82 std::lock_guard lock(threadsPool->Mutex);
83
84 StopFlag = true;
85 }
86
87 Join();
88 }
89
95 void SetStopUnlocked() { StopFlag = true; }
96
102 inline void Join() {
103 if (Thread.joinable())
104 Thread.join();
105 }
106
107private:
117 inline bool TerminateWait() const {
118 return threadsPool->HasWork() || StopFlag;
119 }
120
129 void Run() {
130 for (;;) {
131 std::unique_lock lock(threadsPool->Mutex);
132 if (!TerminateWait())
133 threadsPool->Condition.wait(lock, [this] { return TerminateWait(); });
134
135 while (threadsPool->HasWork() && !StopFlag) {
136 const std::shared_ptr<Job> job =
137 std::move(threadsPool->JobsQueue.front());
138 threadsPool->JobsQueue.pop();
139 lock.unlock();
140
141 job->DoWork();
142
143 {
144 std::lock_guard lockCount(threadsPool->FinishMutex);
145 threadsPool->FinishCount += job->GetJobCount();
146 }
147 lock.lock();
148 }
149
150 if (StopFlag)
151 break;
152 lock.unlock();
153 threadsPool->NotifyFinish();
154 }
155 }
156
157 ThreadsPool
158 *threadsPool;
159 std::thread Thread;
160 bool StopFlag;
162};
163
164} // namespace Utils
165
166#endif // !__WORKER_THREAD_H_
ThreadsPool class for holding and controlling a pool of threads.
Definition ThreadsPool.h:38
void Join()
Join the thread.
void Stop()
Stop the thread.
WorkerThread(ThreadsPool *threadsPool)
Construct a new Worker Thread object.
void Start()
Start the thread.
void SetStopUnlocked()
Set the stop flag without locking it.
~WorkerThread()
Destroy the Worker Thread object.
Definition Alias.h:20