/Users/eugenesiegel/btc/bitcoin/src/semaphore_grant.h
Line | Count | Source (jump to first uncovered line) |
1 | | // Copyright (c) 2009-2010 Satoshi Nakamoto |
2 | | // Copyright (c) 2009-present The Bitcoin Core developers |
3 | | // Distributed under the MIT software license, see the accompanying |
4 | | // file COPYING or http://www.opensource.org/licenses/mit-license.php. |
5 | | |
6 | | #ifndef BITCOIN_SEMAPHORE_GRANT_H |
7 | | #define BITCOIN_SEMAPHORE_GRANT_H |
8 | | |
9 | | #include <semaphore> |
10 | | |
11 | | /** RAII-style semaphore lock */ |
12 | | template <std::ptrdiff_t LeastMaxValue = std::counting_semaphore<>::max()> |
13 | | class CountingSemaphoreGrant |
14 | | { |
15 | | private: |
16 | | std::counting_semaphore<LeastMaxValue>* sem; |
17 | | bool fHaveGrant; |
18 | | |
19 | | public: |
20 | | void Acquire() noexcept |
21 | 0 | { |
22 | 0 | if (fHaveGrant) { |
23 | 0 | return; |
24 | 0 | } |
25 | 0 | sem->acquire(); |
26 | 0 | fHaveGrant = true; |
27 | 0 | } |
28 | | |
29 | | void Release() noexcept |
30 | 116k | { |
31 | 116k | if (!fHaveGrant) { |
32 | 116k | return; |
33 | 116k | } |
34 | 0 | sem->release(); |
35 | 0 | fHaveGrant = false; |
36 | 0 | } |
37 | | |
38 | | bool TryAcquire() noexcept |
39 | 0 | { |
40 | 0 | if (!fHaveGrant && sem->try_acquire()) { |
41 | 0 | fHaveGrant = true; |
42 | 0 | } |
43 | 0 | return fHaveGrant; |
44 | 0 | } |
45 | | |
46 | | // Disallow copy. |
47 | | CountingSemaphoreGrant(const CountingSemaphoreGrant&) = delete; |
48 | | CountingSemaphoreGrant& operator=(const CountingSemaphoreGrant&) = delete; |
49 | | |
50 | | // Allow move. |
51 | | CountingSemaphoreGrant(CountingSemaphoreGrant&& other) noexcept |
52 | 0 | { |
53 | 0 | sem = other.sem; |
54 | 0 | fHaveGrant = other.fHaveGrant; |
55 | 0 | other.fHaveGrant = false; |
56 | 0 | other.sem = nullptr; |
57 | 0 | } |
58 | | |
59 | | CountingSemaphoreGrant& operator=(CountingSemaphoreGrant&& other) noexcept |
60 | 0 | { |
61 | 0 | Release(); |
62 | 0 | sem = other.sem; |
63 | 0 | fHaveGrant = other.fHaveGrant; |
64 | 0 | other.fHaveGrant = false; |
65 | 0 | other.sem = nullptr; |
66 | 0 | return *this; |
67 | 0 | } |
68 | | |
69 | 116k | CountingSemaphoreGrant() noexcept : sem(nullptr), fHaveGrant(false) {} |
70 | | |
71 | 0 | explicit CountingSemaphoreGrant(std::counting_semaphore<LeastMaxValue>& sema, bool fTry = false) noexcept : sem(&sema), fHaveGrant(false) |
72 | 0 | { |
73 | 0 | if (fTry) { |
74 | 0 | TryAcquire(); |
75 | 0 | } else { |
76 | 0 | Acquire(); |
77 | 0 | } |
78 | 0 | } |
79 | | |
80 | | ~CountingSemaphoreGrant() |
81 | 116k | { |
82 | 116k | Release(); |
83 | 116k | } |
84 | | |
85 | | explicit operator bool() const noexcept |
86 | 0 | { |
87 | 0 | return fHaveGrant; |
88 | 0 | } |
89 | | }; |
90 | | |
91 | | using BinarySemaphoreGrant = CountingSemaphoreGrant<1>; |
92 | | |
93 | | #endif // BITCOIN_SEMAPHORE_GRANT_H |