-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemaphore.hpp
More file actions
82 lines (62 loc) · 2.58 KB
/
semaphore.hpp
File metadata and controls
82 lines (62 loc) · 2.58 KB
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
#pragma once
#include "condition_variable.hpp"
#include "memory.hpp"
namespace ift630 {
class Semaphore final {
ConditionVariable<size_t> cv;
public:
Semaphore() noexcept = default;
explicit Semaphore(size_t initial_count) noexcept : cv{initial_count} {}
Semaphore(const Semaphore&) = delete;
Semaphore(Semaphore&&) = delete;
~Semaphore() noexcept = default;
auto operator=(const Semaphore&) -> Semaphore& = delete;
auto operator=(Semaphore &&) -> Semaphore& = delete;
inline void wait() noexcept { enter(); }
inline void enter() noexcept { p(); }
inline void p() noexcept {
cv.wait_mutate([](auto count) { return count != 0; }, [](auto& count) { --count; });
}
inline void signal() noexcept { exit(); }
inline void exit() noexcept { v(); }
inline void v() noexcept {
cv.mutate_notify_one([](auto& count) { ++count; });
}
};
class CopySemaphore final {
shared_ptr<Semaphore> semaphore{};
public:
CopySemaphore() noexcept : semaphore{std::make_shared<Semaphore>()} {}
explicit CopySemaphore(size_t initial_count) noexcept
: semaphore{std::make_shared<Semaphore>(initial_count)} {}
CopySemaphore(const CopySemaphore&) noexcept = default;
CopySemaphore(CopySemaphore&&) noexcept = default;
~CopySemaphore() noexcept = default;
auto operator=(const CopySemaphore&) noexcept -> CopySemaphore& = default;
auto operator=(CopySemaphore&&) noexcept -> CopySemaphore& = default;
inline void wait() const noexcept { enter(); }
inline void enter() const noexcept { p(); }
inline void p() const noexcept { semaphore->p(); }
inline void signal() const noexcept { exit(); }
inline void exit() const noexcept { v(); }
inline void v() const noexcept { semaphore->v(); }
};
class MoveSemaphore final {
unique_ptr<Semaphore> semaphore{};
public:
MoveSemaphore() noexcept : semaphore{std::make_unique<Semaphore>()} {}
explicit MoveSemaphore(size_t initial_count) noexcept
: semaphore{std::make_unique<Semaphore>(initial_count)} {}
MoveSemaphore(const MoveSemaphore&) noexcept = delete;
MoveSemaphore(MoveSemaphore&&) noexcept = default;
~MoveSemaphore() noexcept = default;
auto operator=(const MoveSemaphore&) noexcept -> MoveSemaphore& = delete;
auto operator=(MoveSemaphore&&) noexcept -> MoveSemaphore& = default;
inline void wait() const noexcept { enter(); }
inline void enter() const noexcept { p(); }
inline void p() const noexcept { semaphore->p(); }
inline void signal() const noexcept { exit(); }
inline void exit() const noexcept { v(); }
inline void v() const noexcept { semaphore->v(); }
};
}; // namespace ift630