Coverage Report

Created: 2026-09-21 19:49

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
6.02k
    {
22
6.02k
        if (fHaveGrant) {
23
0
            return;
24
0
        }
25
6.02k
        sem->acquire();
26
6.02k
        fHaveGrant = true;
27
6.02k
    }
28
29
    void Release() noexcept
30
10.0k
    {
31
10.0k
        if (!fHaveGrant) {
32
3.85k
            return;
33
3.85k
        }
34
6.19k
        sem->release();
35
6.19k
        fHaveGrant = false;
36
6.19k
    }
37
38
    bool TryAcquire() noexcept
39
170
    {
40
170
        if (!fHaveGrant && sem->try_acquire()) {
41
170
            fHaveGrant = true;
42
170
        }
43
170
        return fHaveGrant;
44
170
    }
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
643
    {
61
643
        Release();
62
643
        sem = other.sem;
63
643
        fHaveGrant = other.fHaveGrant;
64
643
        other.fHaveGrant = false;
65
643
        other.sem = nullptr;
66
643
        return *this;
67
643
    }
68
69
2.23k
    CountingSemaphoreGrant() noexcept : sem(nullptr), fHaveGrant(false) {}
70
71
6.19k
    explicit CountingSemaphoreGrant(std::counting_semaphore<LeastMaxValue>& sema, bool fTry = false) noexcept : sem(&sema), fHaveGrant(false)
72
6.19k
    {
73
6.19k
        if (fTry) {
74
170
            TryAcquire();
75
6.02k
        } else {
76
6.02k
            Acquire();
77
6.02k
        }
78
6.19k
    }
79
80
    ~CountingSemaphoreGrant()
81
8.44k
    {
82
8.44k
        Release();
83
8.44k
    }
84
85
    explicit operator bool() const noexcept
86
172
    {
87
172
        return fHaveGrant;
88
172
    }
89
};
90
91
using BinarySemaphoreGrant = CountingSemaphoreGrant<1>;
92
93
#endif // BITCOIN_SEMAPHORE_GRANT_H