PCB Environment 2

Loading...
Searching...
No Matches
LockStep.hpp
1
2#ifndef GYM_PCB_UI_LOCKSTEP_H
3#define GYM_PCB_UI_LOCKSTEP_H
4
5#include <mutex>
6#include <condition_variable>
7
8 class StepLock
9{
10 public:
11 StepLock(uint granularity = 0) : mGranularity(granularity) { }
12 void setGranularity(uint n) { if (n == 0 && mGranularity != 0) signal(); mGranularity = n; }
13 uint getGranularity() const { return mGranularity; }
14 void wait(uint granularity = 1);
15 void signal();
16 private:
17 std::mutex mLock;
18 std::condition_variable mCV;
19 uint mSeq{0};
20 uint mGranularity{0};
21};
22
23 inline void StepLock::wait(uint granularity)
24{
25 if (granularity <= mGranularity) {
26 std::unique_lock lock(mLock);
27 mCV.wait(lock, [this, curr = mSeq]{ return mSeq != curr; });
28 }
29}
30 inline void StepLock::signal()
31{
32 if (mGranularity) {
33 {
34 std::lock_guard lock(mLock);
35 mSeq++;
36 }
37 mCV.notify_one();
38 }
39}
40
41#endif // GYM_PCB_UI_LOCKSTEP_H