Maestro 0.1.0
Unified interface for quantum circuit simulation
Loading...
Searching...
No Matches
WorkerThread.h
Go to the documentation of this file.
1
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>
35 public:
44 explicit WorkerThread(ThreadsPool *threadsPool)
45 : threadsPool(threadsPool), StopFlag(false) {
46 Thread = std::thread(&WorkerThread::Run, this);
47 }
48
56
62 void Start() {
63 if (Thread.joinable()) 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()) return;
79
80 {
81 std::lock_guard lock(threadsPool->Mutex);
82
83 StopFlag = true;
84 }
85
86 Join();
87 }
88
94 void SetStopUnlocked() { StopFlag = true; }
95
101 inline void Join() {
102 if (Thread.joinable()) Thread.join();
103 }
104
105 private:
115 inline bool TerminateWait() const {
116 return threadsPool->HasWork() || StopFlag;
117 }
118
127 void Run() {
128 for (;;) {
129 std::unique_lock lock(threadsPool->Mutex);
130 if (!TerminateWait())
131 threadsPool->Condition.wait(lock, [this] { return TerminateWait(); });
132
133 while (threadsPool->HasWork() && !StopFlag) {
134 const std::shared_ptr<Job> job =
135 std::move(threadsPool->JobsQueue.front());
136 threadsPool->JobsQueue.pop();
137 lock.unlock();
138
139 job->DoWork();
140
141 {
142 std::lock_guard lockCount(threadsPool->FinishMutex);
143 threadsPool->FinishCount += job->GetJobCount();
144 }
145 lock.lock();
146 }
147
148 if (StopFlag) break;
149 lock.unlock();
150 threadsPool->NotifyFinish();
151 }
152 }
153
154 ThreadsPool
155 *threadsPool;
156 std::thread Thread;
157 bool StopFlag;
159};
160
161} // namespace Utils
162
163#endif // !__WORKER_THREAD_H_
ThreadsPool class for holding and controlling a pool of threads.
Definition ThreadsPool.h:39
WorkerThread class for a thread in a threads pool.
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