Skip to content

Commit f21365c

Browse files
committed
threading: replace CountingSemaphore with std::counting_semaphore
1 parent 1acacfb commit f21365c

File tree

1 file changed

+4
-53
lines changed

1 file changed

+4
-53
lines changed

src/sync.h

Lines changed: 4 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -301,64 +301,15 @@ inline MutexType* MaybeCheckNotHeld(MutexType* m) LOCKS_EXCLUDED(m) LOCK_RETURNE
301301
//! gcc and the -Wreturn-stack-address flag in clang, both enabled by default.
302302
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
303303

304-
/** An implementation of a semaphore.
305-
*
306-
* See https://en.wikipedia.org/wiki/Semaphore_(programming)
307-
*/
308-
template <std::ptrdiff_t LeastMaxValue = std::counting_semaphore<>::max()>
309-
class CountingSemaphore
310-
{
311-
private:
312-
std::condition_variable condition;
313-
std::mutex mutex;
314-
int value;
315-
316-
public:
317-
explicit CountingSemaphore(int init) noexcept : value(init) {}
318-
319-
// Disallow default construct, copy, move.
320-
CountingSemaphore() = delete;
321-
CountingSemaphore(const CountingSemaphore&) = delete;
322-
CountingSemaphore(CountingSemaphore&&) = delete;
323-
CountingSemaphore& operator=(const CountingSemaphore&) = delete;
324-
CountingSemaphore& operator=(CountingSemaphore&&) = delete;
325-
326-
void acquire() noexcept
327-
{
328-
std::unique_lock<std::mutex> lock(mutex);
329-
condition.wait(lock, [&]() { return value >= 1; });
330-
value--;
331-
}
332-
333-
bool try_acquire() noexcept
334-
{
335-
std::lock_guard<std::mutex> lock(mutex);
336-
if (value < 1) {
337-
return false;
338-
}
339-
value--;
340-
return true;
341-
}
342-
343-
void release() noexcept
344-
{
345-
{
346-
std::lock_guard<std::mutex> lock(mutex);
347-
value++;
348-
}
349-
condition.notify_one();
350-
}
351-
};
352-
353-
using BinarySemaphore = CountingSemaphore<1>;
354-
using Semaphore = CountingSemaphore<>;
304+
using BinarySemaphore = std::binary_semaphore;
305+
using Semaphore = std::counting_semaphore<>;
355306

356307
/** RAII-style semaphore lock */
357308
template <std::ptrdiff_t LeastMaxValue = std::counting_semaphore<>::max()>
358309
class CountingSemaphoreGrant
359310
{
360311
private:
361-
CountingSemaphore<LeastMaxValue>* sem;
312+
std::counting_semaphore<LeastMaxValue>* sem;
362313
bool fHaveGrant;
363314

364315
public:
@@ -413,7 +364,7 @@ class CountingSemaphoreGrant
413364

414365
CountingSemaphoreGrant() noexcept : sem(nullptr), fHaveGrant(false) {}
415366

416-
explicit CountingSemaphoreGrant(CountingSemaphore<LeastMaxValue>& sema, bool fTry = false) noexcept : sem(&sema), fHaveGrant(false)
367+
explicit CountingSemaphoreGrant(std::counting_semaphore<LeastMaxValue>& sema, bool fTry = false) noexcept : sem(&sema), fHaveGrant(false)
417368
{
418369
if (fTry) {
419370
TryAcquire();

0 commit comments

Comments
 (0)