Coverage Report

Created: 2026-10-19 15:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/semaphore_grant.h
Line
Count
Source
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
5.09k
    {
22
5.09k
        if (fHaveGrant) {
23
0
            return;
24
0
        }
25
5.09k
        sem->acquire();
26
5.09k
        fHaveGrant = true;
27
5.09k
    }
28
29
    void Release() noexcept
30
9.25k
    {
31
9.25k
        if (!fHaveGrant) {
32
3.98k
            return;
33
3.98k
        }
34
5.27k
        sem->release();
35
5.27k
        fHaveGrant = false;
36
5.27k
    }
37
38
    bool TryAcquire() noexcept
39
179
    {
40
179
        if (!fHaveGrant && sem->try_acquire()) {
41
179
            fHaveGrant = true;
42
179
        }
43
179
        return fHaveGrant;
44
179
    }
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
12
    {
53
12
        sem = other.sem;
54
12
        fHaveGrant = other.fHaveGrant;
55
12
        other.fHaveGrant = false;
56
12
        other.sem = nullptr;
57
12
    }
58
59
    CountingSemaphoreGrant& operator=(CountingSemaphoreGrant&& other) noexcept
60
668
    {
61
668
        Release();
62
668
        sem = other.sem;
63
668
        fHaveGrant = other.fHaveGrant;
64
668
        other.fHaveGrant = false;
65
668
        other.sem = nullptr;
66
668
        return *this;
67
668
    }
68
69
2.29k
    CountingSemaphoreGrant() noexcept : sem(nullptr), fHaveGrant(false) {}
70
71
5.27k
    explicit CountingSemaphoreGrant(std::counting_semaphore<LeastMaxValue>& sema, bool fTry = false) noexcept : sem(&sema), fHaveGrant(false)
72
5.27k
    {
73
5.27k
        if (fTry) {
74
179
            TryAcquire();
75
5.09k
        } else {
76
5.09k
            Acquire();
77
5.09k
        }
78
5.27k
    }
79
80
    ~CountingSemaphoreGrant()
81
7.57k
    {
82
7.57k
        Release();
83
7.57k
    }
84
85
    explicit operator bool() const noexcept
86
181
    {
87
181
        return fHaveGrant;
88
181
    }
89
};
90
91
using BinarySemaphoreGrant = CountingSemaphoreGrant<1>;
92
93
#endif // BITCOIN_SEMAPHORE_GRANT_H