-
Notifications
You must be signed in to change notification settings - Fork 3
/
semaphore.h
103 lines (101 loc) · 2.08 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#ifndef SEMAPHORE_H
#define SEMAPHORE_H
#include <mutex>
#include <condition_variable>
#include <algorithm>
namespace LQF
{
class Semaphore
{
public:
struct closed_exception {};
public:
explicit Semaphore(size_t cnt = 0)
: count_(cnt)
, opened_(true)
{}
~Semaphore(){}
void open()
{
std::lock_guard<std::mutex> _(mutex_);
opened_ = true;
}
void close()
{
std::lock_guard<std::mutex> _(mutex_);
opened_ = false;
event_.notify_all();
}
void wait()
{
std::unique_lock<std::mutex> lck(mutex_);
event_.wait(lck, [this]
{
if (!opened_)
{
throw closed_exception();
}
return count_ > 0;
});
--count_;
}
void post(size_t n = 1)
{
std::unique_lock<std::mutex> lck(mutex_);
count_ += n;
event_.notify(lck, n);
}
protected:
class Guard
{
public:
explicit Guard(size_t& waiters)
: waiters_(waiters)
{
++waiters_;
}
~Guard()
{
--waiters_;
}
private:
size_t & waiters_;
};
class Event
{
public:
void wait(std::unique_lock<std::mutex>& lck)
{
Guard _(waiters_);
cnd_.wait(lck);
}
template <typename F>
void wait(std::unique_lock<std::mutex>& lck, F f)
{
Guard _(waiters_);
cnd_.wait(lck, f);
}
void notify(std::unique_lock<std::mutex>& lck, size_t n = 1)
{
auto times = std::min(n, waiters_);
for (size_t i = 0; i < times; i++)
{
cnd_.notify_one();
}
}
void notify_all()
{
cnd_.notify_all();
}
private:
std::condition_variable cnd_;
size_t waiters_{ 0 };
};
private:
std::mutex mutex_;
Event event_;
size_t count_{ 0 };
bool opened_{ false };
};
}
#endif // SEMAPHORE_H