-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSemaphore.h
67 lines (58 loc) · 1.35 KB
/
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**************************************************************************
* @file: Semaphore.h
* @brief:
*
* Copyright (c) 2022 O-Net Communications Inc.
*************************************************************************/
#pragma once
#include <chrono>
#include <condition_variable>
#include <mutex>
namespace cppbase {
class Semaphore
{
public:
Semaphore(int32_t count = 0) : m_count(count) {}
~Semaphore() { Reset(); }
void Notify()
{
{
std::unique_lock<std::mutex> lock(m_mutex);
m_count++;
}
// notify the waiting thread
m_cv.notify_one();
}
void Wait()
{
std::unique_lock<std::mutex> lock(m_mutex);
while (m_count == 0)
{
// wait on the mutex until notify is called
m_cv.wait(lock);
}
m_count--;
}
bool TryWait(std::chrono::microseconds timeout /*us*/)
{
std::unique_lock<std::mutex> lock(m_mutex);
while (m_count == 0)
{
m_cv.wait_for(lock, timeout);
if (m_count == 0)
return false;
}
m_count--;
return true;
}
void Reset()
{
m_cv.notify_all();
m_count = 0;
}
private:
std::mutex m_mutex;
std::condition_variable m_cv;
int32_t m_count;
};
} // namespace cppbase