3#include "gaia/config/config.h"
5#if GAIA_PLATFORM_WINDOWS
8 #include "gaia/mt/win32.h"
9#elif GAIA_PLATFORM_APPLE
10 #include <TargetConditionals.h>
11 #include <dispatch/dispatch.h>
15 #include <semaphore.h>
22#if GAIA_PLATFORM_WINDOWS
24#elif GAIA_PLATFORM_APPLE
25 dispatch_semaphore_t m_handle;
37 void init(int32_t count) {
38#if GAIA_PLATFORM_WINDOWS
39 m_handle = ::CreateSemaphoreExW(
nullptr, count, INT_MAX,
nullptr, 0, win32::SemaphoreAllAccess);
40 GAIA_ASSERT(m_handle !=
nullptr);
41#elif GAIA_PLATFORM_APPLE
42 m_handle = dispatch_semaphore_create(count);
43 GAIA_ASSERT(m_handle !=
nullptr);
45 [[maybe_unused]]
int ret = sem_init(&m_handle, 0, (
unsigned int)count);
46 GAIA_ASSERT(ret == 0);
52#if GAIA_PLATFORM_WINDOWS
53 if (m_handle !=
nullptr) {
54 ::CloseHandle(m_handle);
57#elif GAIA_PLATFORM_APPLE
62 [[maybe_unused]]
int ret = sem_destroy(&m_handle);
63 GAIA_ASSERT(ret == 0);
81 GAIA_ASSERT(count > 0);
83#if GAIA_PLATFORM_WINDOWS
84 [[maybe_unused]]
long prev = 0;
85 [[maybe_unused]]
int res = ::ReleaseSemaphore(m_handle, count, &prev);
86 GAIA_ASSERT(res != 0);
87#elif GAIA_PLATFORM_APPLE
89 dispatch_semaphore_signal(m_handle);
90 }
while ((--count) != 0);
93 [[maybe_unused]]
const auto ret = sem_post(&m_handle);
94 GAIA_ASSERT(ret == 0);
95 }
while ((--count) != 0);
104#if GAIA_PLATFORM_WINDOWS
105 GAIA_ASSERT(m_handle !=
nullptr);
106 const unsigned long ret = ::WaitForSingleObject(m_handle, win32::Infinite);
107 GAIA_ASSERT(ret == win32::WaitObject0);
108 return (ret == win32::WaitObject0);
109#elif GAIA_PLATFORM_APPLE
110 const auto res = dispatch_semaphore_wait(m_handle, DISPATCH_TIME_FOREVER);
111 GAIA_ASSERT(res == 0);
116 res = sem_wait(&m_handle);
117 }
while (res == -1 && errno == EINTR);
119 GAIA_ASSERT(res == 0);
Portable counting semaphore with indefinite waits.
Definition semaphore.h:21
Semaphore(int32_t count=0)
Creates a semaphore with an initial count.
Definition semaphore.h:70
void release(int32_t count)
Increments semaphore count by the specified amount.
Definition semaphore.h:80
bool wait()
Decrements semaphore count by 1. If the count is already 0, it waits indefinitely until semaphore cou...
Definition semaphore.h:103