3#include "gaia/config/config.h"
5#if GAIA_PLATFORM_WINDOWS
7#elif GAIA_PLATFORM_APPLE
8 #include <TargetConditionals.h>
9 #include <dispatch/dispatch.h>
13 #include <semaphore.h>
20#if GAIA_PLATFORM_WINDOWS
22#elif GAIA_PLATFORM_APPLE
23 dispatch_semaphore_t m_handle;
35 void init(int32_t count) {
36#if GAIA_PLATFORM_WINDOWS
37 m_handle = (
void*)::CreateSemaphoreExW(NULL, count, INT_MAX, NULL, 0, SEMAPHORE_ALL_ACCESS);
38 GAIA_ASSERT(m_handle != NULL);
39#elif GAIA_PLATFORM_APPLE
40 m_handle = dispatch_semaphore_create(count);
41 GAIA_ASSERT(m_handle !=
nullptr);
43 [[maybe_unused]]
int ret = sem_init(&m_handle, 0, count);
44 GAIA_ASSERT(ret == 0);
50#if GAIA_PLATFORM_WINDOWS
51 if (m_handle != NULL) {
52 ::CloseHandle((HANDLE)m_handle);
55#elif GAIA_PLATFORM_APPLE
60 [[maybe_unused]]
int ret = sem_destroy(&m_handle);
61 GAIA_ASSERT(ret == 0);
79 GAIA_ASSERT(count > 0);
81#if GAIA_PLATFORM_WINDOWS
82 [[maybe_unused]] LONG prev = 0;
83 [[maybe_unused]] BOOL res = ::ReleaseSemaphore(m_handle, count, &prev);
84 GAIA_ASSERT(res != 0);
85#elif GAIA_PLATFORM_APPLE
87 dispatch_semaphore_signal(m_handle);
88 }
while ((--count) != 0);
91 [[maybe_unused]]
const auto ret = sem_post(&m_handle);
92 GAIA_ASSERT(ret == 0);
93 }
while ((--count) != 0);
102#if GAIA_PLATFORM_WINDOWS
103 GAIA_ASSERT(m_handle != (
void*)ERROR_INVALID_HANDLE);
104 DWORD ret = ::WaitForSingleObject(m_handle, INFINITE);
105 GAIA_ASSERT(ret == WAIT_OBJECT_0);
106 return (ret == WAIT_OBJECT_0);
107#elif GAIA_PLATFORM_APPLE
108 const auto res = dispatch_semaphore_wait(m_handle, DISPATCH_TIME_FOREVER);
109 GAIA_ASSERT(res == 0);
114 res = sem_wait(&m_handle);
115 }
while (res == -1 && errno == EINTR);
117 GAIA_ASSERT(res == 0);
Portable counting semaphore with indefinite waits.
Definition semaphore.h:19
Semaphore(int32_t count=0)
Creates a semaphore with an initial count.
Definition semaphore.h:68
void release(int32_t count)
Increments semaphore count by the specified amount.
Definition semaphore.h:78
bool wait()
Decrements semaphore count by 1. If the count is already 0, it waits indefinitely until semaphore cou...
Definition semaphore.h:101