diff options
| author | Mikhail Romanko <me@blankhex.com> | 2025-06-27 12:39:55 +0300 |
|---|---|---|
| committer | Mikhail Romanko <me@blankhex.com> | 2025-06-27 12:39:55 +0300 |
| commit | f82f87cc419ec045fddbcc5de86953da2691bb1b (patch) | |
| tree | e3831286e64b7bf1e8adc36ef6a819d5f6a3ee0a /src/Platform/Posix/Semaphore.c | |
| parent | 703fb0f2407622a8d82abd9ae18fbde81688773f (diff) | |
| download | bhlib-f82f87cc419ec045fddbcc5de86953da2691bb1b.tar.gz | |
Fix semaphore implementation for MacOS
Diffstat (limited to 'src/Platform/Posix/Semaphore.c')
| -rw-r--r-- | src/Platform/Posix/Semaphore.c | 37 |
1 files changed, 26 insertions, 11 deletions
diff --git a/src/Platform/Posix/Semaphore.c b/src/Platform/Posix/Semaphore.c index 9482201..4c64786 100644 --- a/src/Platform/Posix/Semaphore.c +++ b/src/Platform/Posix/Semaphore.c @@ -61,7 +61,8 @@ int BH_SemaphoreWaitFor(BH_Semaphore *semaphore, uint32_t timeout) { struct timespec ts; - convertToTimespec(&ts, timeout); + if (convertToTimespec(&ts, timeout)) + return BH_ERROR; switch (sem_timedwait(&semaphore->handle, &ts)) { @@ -111,14 +112,19 @@ void BH_SemaphoreFree(BH_Semaphore *semaphore) int BH_SemaphorePost(BH_Semaphore *semaphore) { + int result; + /* Increase semaphore value */ - pthread_mutex_lock(&semaphore->mutex); + if (pthread_mutex_lock(&semaphore->mutex)) + return BH_ERROR; + + result = BH_OK; semaphore->count++; - if (semaphore->waiters) - pthread_cond_signal(&semaphore->condition); - pthread_mutex_unlock(&semaphore->mutex); + if (semaphore->waiters && pthread_cond_signal(&semaphore->condition)) + result = BH_ERROR; - return BH_OK; + pthread_mutex_unlock(&semaphore->mutex); + return result; } @@ -127,11 +133,19 @@ int BH_SemaphoreWait(BH_Semaphore *semaphore) int result; /* Wait until semaphore count is not zero */ - result = BH_ERROR; - pthread_mutex_lock(&semaphore->mutex); + if (pthread_mutex_lock(&semaphore->mutex)) + return BH_ERROR; + + result = BH_OK; semaphore->waiters++; - while (!semaphore->count) - pthread_cond_wait(&semaphore->condition, &semaphore->mutex); + while (!semaphore->count) { + result = pthread_cond_wait(&semaphore->condition, &semaphore->mutex); + if (result && result != ETIMEDOUT) { + result = BH_ERROR; + break; + } + result = BH_OK; + } semaphore->waiters--; semaphore->count--; pthread_mutex_unlock(&semaphore->mutex); @@ -165,7 +179,8 @@ int BH_SemaphoreWaitFor(BH_Semaphore *semaphore, struct timespec ts; /* Calculate absoulute time for timed wait */ - convertToTimespec(&ts, timeout); + if (convertToTimespec(&ts, timeout)) + return BH_ERROR; result = BH_OK; /* Wait until semaphore count is not zero or timeout */ |
