Gaia-ECS v1.0.0
A simple and powerful entity component system
Loading...
Searching...
No Matches
semaphore_fast.h
1#pragma once
2
3#include "gaia/config/config.h"
4
5#include <atomic>
6
7#include "gaia/mt/semaphore.h"
8
9namespace gaia {
10 namespace mt {
12 class GAIA_API SemaphoreFast final {
13 Semaphore m_sem;
14 std::atomic_int32_t m_cnt;
15
16 SemaphoreFast(SemaphoreFast&&) = delete;
17 SemaphoreFast(const SemaphoreFast&) = delete;
18 SemaphoreFast& operator=(SemaphoreFast&&) = delete;
19 SemaphoreFast& operator=(const SemaphoreFast&) = delete;
20
21 public:
24 explicit SemaphoreFast(int32_t count = 0): m_sem(count), m_cnt(0) {}
25 ~SemaphoreFast() = default;
26
29 void release(int32_t count = 1) {
30 const int32_t prevCount = m_cnt.fetch_add(count, std::memory_order_release);
31 int32_t toRelease = -prevCount;
32 if (count < toRelease)
33 toRelease = count;
34
35 if (toRelease > 0)
36 m_sem.release(toRelease);
37 }
38
43 bool wait() {
44 const int32_t oldCount = m_cnt.fetch_sub(1, std::memory_order_acquire);
45 bool result = true;
46 if (oldCount <= 0)
47 result = m_sem.wait();
48
49 return result;
50 }
51 };
52 } // namespace mt
53} // namespace gaia
An optimized version of Semaphore that avoids expensive system calls when the counter is greater than...
Definition semaphore_fast.h:12
bool wait()
Decrements semaphore count by 1. If the count is already 0, it waits indefinitely until semaphore cou...
Definition semaphore_fast.h:43
SemaphoreFast(int32_t count=0)
Creates a semaphore with the requested initial system-semaphore count.
Definition semaphore_fast.h:24
void release(int32_t count=1)
Increments semaphore count by the specified amount.
Definition semaphore_fast.h:29
Portable counting semaphore with indefinite waits.
Definition semaphore.h:19