forked from wirenboard/wb-mqtt-serial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_semaphore.h
37 lines (34 loc) · 871 Bytes
/
binary_semaphore.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#pragma once
#include <chrono>
#include <mutex>
#include <memory>
#include <condition_variable>
class TBinarySemaphore {
public:
template<class Clock, class Duration>
bool Wait(const std::chrono::time_point<Clock, Duration>& until)
{
std::unique_lock<std::mutex> lock(Mutex);
bool r = Cond.wait_until(lock, until, [this](){ return _Signaled; });
_Signaled = false;
return r;
}
bool TryWait()
{
std::unique_lock<std::mutex> lock(Mutex);
bool r = _Signaled;
_Signaled = false;
return r;
}
void Signal()
{
std::unique_lock<std::mutex> lock(Mutex);
_Signaled = true;
Cond.notify_all();
}
private:
bool _Signaled = false;
std::mutex Mutex;
std::condition_variable Cond;
};
typedef std::shared_ptr<TBinarySemaphore> PBinarySemaphore;