From f21365c4fc7f6f45194f5b725192f0054e2daf13 Mon Sep 17 00:00:00 2001 From: Cory Fields Date: Thu, 8 May 2025 18:59:25 +0000 Subject: [PATCH] threading: replace CountingSemaphore with std::counting_semaphore --- src/sync.h | 57 ++++-------------------------------------------------- 1 file changed, 4 insertions(+), 53 deletions(-) diff --git a/src/sync.h b/src/sync.h index bef029427ab..6f2830fd93b 100644 --- a/src/sync.h +++ b/src/sync.h @@ -301,64 +301,15 @@ inline MutexType* MaybeCheckNotHeld(MutexType* m) LOCKS_EXCLUDED(m) LOCK_RETURNE //! gcc and the -Wreturn-stack-address flag in clang, both enabled by default. #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) -/** An implementation of a semaphore. - * - * See https://en.wikipedia.org/wiki/Semaphore_(programming) - */ -template ::max()> -class CountingSemaphore -{ -private: - std::condition_variable condition; - std::mutex mutex; - int value; - -public: - explicit CountingSemaphore(int init) noexcept : value(init) {} - - // Disallow default construct, copy, move. - CountingSemaphore() = delete; - CountingSemaphore(const CountingSemaphore&) = delete; - CountingSemaphore(CountingSemaphore&&) = delete; - CountingSemaphore& operator=(const CountingSemaphore&) = delete; - CountingSemaphore& operator=(CountingSemaphore&&) = delete; - - void acquire() noexcept - { - std::unique_lock lock(mutex); - condition.wait(lock, [&]() { return value >= 1; }); - value--; - } - - bool try_acquire() noexcept - { - std::lock_guard lock(mutex); - if (value < 1) { - return false; - } - value--; - return true; - } - - void release() noexcept - { - { - std::lock_guard lock(mutex); - value++; - } - condition.notify_one(); - } -}; - -using BinarySemaphore = CountingSemaphore<1>; -using Semaphore = CountingSemaphore<>; +using BinarySemaphore = std::binary_semaphore; +using Semaphore = std::counting_semaphore<>; /** RAII-style semaphore lock */ template ::max()> class CountingSemaphoreGrant { private: - CountingSemaphore* sem; + std::counting_semaphore* sem; bool fHaveGrant; public: @@ -413,7 +364,7 @@ public: CountingSemaphoreGrant() noexcept : sem(nullptr), fHaveGrant(false) {} - explicit CountingSemaphoreGrant(CountingSemaphore& sema, bool fTry = false) noexcept : sem(&sema), fHaveGrant(false) + explicit CountingSemaphoreGrant(std::counting_semaphore& sema, bool fTry = false) noexcept : sem(&sema), fHaveGrant(false) { if (fTry) { TryAcquire();