Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Copyright (c) 2009-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#ifndef BITCOIN_SEMAPHORE_GRANT_H7#define BITCOIN_SEMAPHORE_GRANT_H9#include <semaphore>11/** RAII-style semaphore lock */12template <std::ptrdiff_t LeastMaxValue = std::counting_semaphore<>::max()>13class CountingSemaphoreGrant14{15private:16std::counting_semaphore<LeastMaxValue>* sem;17bool fHaveGrant;19public:20void Acquire() noexcept21{22if (fHaveGrant) {23return;24}25sem->acquire();26fHaveGrant = true;27}29void Release() noexcept30{31if (!fHaveGrant) {32return;33}34sem->release();35fHaveGrant = false;36}38bool TryAcquire() noexcept39{40if (!fHaveGrant && sem->try_acquire()) {41fHaveGrant = true;42}43return fHaveGrant;44}46// Disallow copy.47CountingSemaphoreGrant(const CountingSemaphoreGrant&) = delete;48CountingSemaphoreGrant& operator=(const CountingSemaphoreGrant&) = delete;50// Allow move.51CountingSemaphoreGrant(CountingSemaphoreGrant&& other) noexcept52{53sem = other.sem;54fHaveGrant = other.fHaveGrant;55other.fHaveGrant = false;56other.sem = nullptr;57}59CountingSemaphoreGrant& operator=(CountingSemaphoreGrant&& other) noexcept60{61Release();62sem = other.sem;63fHaveGrant = other.fHaveGrant;64other.fHaveGrant = false;65other.sem = nullptr;66return *this;67}69CountingSemaphoreGrant() noexcept : sem(nullptr), fHaveGrant(false) {}71explicit CountingSemaphoreGrant(std::counting_semaphore<LeastMaxValue>& sema, bool fTry = false) noexcept : sem(&sema), fHaveGrant(false)72{73if (fTry) {74TryAcquire();75} else {76Acquire();77}78}80~CountingSemaphoreGrant()81{82Release();83}85explicit operator bool() const noexcept86{87return fHaveGrant;88}89};91using BinarySemaphoreGrant = CountingSemaphoreGrant<1>;93#endif // BITCOIN_SEMAPHORE_GRANT_H