summaryrefslogtreecommitdiffstats
path: root/src/darwin/sem_darwin.c
diff options
context:
space:
mode:
authorDavid Robillard <d@drobilla.net>2022-10-23 12:55:40 -0400
committerDavid Robillard <d@drobilla.net>2022-10-23 13:26:00 -0400
commite883ea50dd1154294e21e946e391dd38e04d6527 (patch)
tree2019aecf50e1eb2f73a2aaf567d0f4573d9efc31 /src/darwin/sem_darwin.c
parent07b1289cd4907aa3defe3fc600f3db1dcefcb719 (diff)
downloadzix-e883ea50dd1154294e21e946e391dd38e04d6527.tar.gz
zix-e883ea50dd1154294e21e946e391dd38e04d6527.tar.bz2
zix-e883ea50dd1154294e21e946e391dd38e04d6527.zip
Split up platform sources
This puts more onus on the build system to do things properly, but it's still easy enough to build, even manually: all the files in the appropriate system subdirectory just need to be included in the build. Otherwise, the several nested levels of preprocessor conditionals get confusing, and clang-format doesn't format code properly.
Diffstat (limited to 'src/darwin/sem_darwin.c')
-rw-r--r--src/darwin/sem_darwin.c68
1 files changed, 68 insertions, 0 deletions
diff --git a/src/darwin/sem_darwin.c b/src/darwin/sem_darwin.c
new file mode 100644
index 0000000..0ace564
--- /dev/null
+++ b/src/darwin/sem_darwin.c
@@ -0,0 +1,68 @@
+// Copyright 2012-2022 David Robillard <d@drobilla.net>
+// SPDX-License-Identifier: ISC
+
+#include "zix/sem.h"
+
+#include "zix/status.h"
+
+#include <mach/mach.h>
+
+#include <stdint.h>
+#include <time.h>
+
+ZixStatus
+zix_sem_init(ZixSem* sem, unsigned val)
+{
+ return semaphore_create(
+ mach_task_self(), &sem->sem, SYNC_POLICY_FIFO, (int)val)
+ ? ZIX_STATUS_ERROR
+ : ZIX_STATUS_SUCCESS;
+}
+
+ZixStatus
+zix_sem_destroy(ZixSem* sem)
+{
+ return semaphore_destroy(mach_task_self(), sem->sem) ? ZIX_STATUS_ERROR
+ : ZIX_STATUS_SUCCESS;
+}
+
+ZixStatus
+zix_sem_post(ZixSem* sem)
+{
+ return semaphore_signal(sem->sem) ? ZIX_STATUS_ERROR : ZIX_STATUS_SUCCESS;
+}
+
+ZixStatus
+zix_sem_wait(ZixSem* sem)
+{
+ kern_return_t r = 0;
+ while ((r = semaphore_wait(sem->sem)) && r == KERN_ABORTED) {
+ // Interrupted, try again
+ }
+
+ return r ? ZIX_STATUS_ERROR : ZIX_STATUS_SUCCESS;
+}
+
+ZixStatus
+zix_sem_try_wait(ZixSem* sem)
+{
+ const mach_timespec_t zero = {0, 0};
+ const kern_return_t r = semaphore_timedwait(sem->sem, zero);
+
+ return (r == KERN_SUCCESS) ? ZIX_STATUS_SUCCESS
+ : (r == KERN_OPERATION_TIMED_OUT) ? ZIX_STATUS_UNAVAILABLE
+ : ZIX_STATUS_ERROR;
+}
+
+ZixStatus
+zix_sem_timed_wait(ZixSem* sem,
+ const uint32_t seconds,
+ const uint32_t nanoseconds)
+{
+ const mach_timespec_t interval = {seconds, (clock_res_t)nanoseconds};
+ const kern_return_t r = semaphore_timedwait(sem->sem, interval);
+
+ return (r == KERN_SUCCESS) ? ZIX_STATUS_SUCCESS
+ : (r == KERN_OPERATION_TIMED_OUT) ? ZIX_STATUS_TIMEOUT
+ : ZIX_STATUS_ERROR;
+}