-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiSemaphore.h
More file actions
45 lines (37 loc) · 847 Bytes
/
MultiSemaphore.h
File metadata and controls
45 lines (37 loc) · 847 Bytes
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
#pragma once
#include <mutex>
#include <condition_variable>
#include <atomic>
class MultiSemaphore {
public:
void lock() {
std::unique_lock<std::mutex> lock(mutex_);
++lockCount;
while (lockCount > 1) {
condition_.wait(lock);
}
}
void wait() {
std::unique_lock<std::mutex> lock(mutex_);
while (lockCount > 0) {
condition_.wait(lock);
}
}
void unlock() {
std::lock_guard<std::mutex> lg(mutex_);
if (lockCount != 0)
--lockCount;
if (lockCount == 0)
condition_.notify_all();
}
void addLock() {
++lockCount;
}
size_t count() {
return lockCount;
}
private:
std::mutex mutex_;
std::condition_variable condition_;
std::atomic_size_t lockCount = 0;
};