2 * Copyright (c) 1994 by Xerox Corporation. All rights reserved.
3 * Copyright (c) 1996 by Silicon Graphics. All rights reserved.
4 * Copyright (c) 1998 by Fergus Henderson. All rights reserved.
5 * Copyright (c) 2000-2009 by Hewlett-Packard Development Company.
8 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
9 * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
11 * Permission is hereby granted to use or copy this program
12 * for any purpose, provided the above notices are retained on all copies.
13 * Permission to modify the code and to distribute modified code is granted,
14 * provided the above notices are retained, and a notice that the code was
15 * modified is included with the above copyright notice.
18 #ifndef GC_DARWIN_SEMAPHORE_H
19 #define GC_DARWIN_SEMAPHORE_H
21 #if !defined(GC_DARWIN_THREADS)
22 #error darwin_semaphore.h included with GC_DARWIN_THREADS not defined
26 This is a very simple semaphore implementation for darwin. It
27 is implemented in terms of pthreads calls so it isn't async signal
28 safe. This isn't a problem because signals aren't used to
29 suspend threads on darwin.
33 pthread_mutex_t mutex;
38 static int sem_init(sem_t *sem, int pshared, int value) {
41 ABORT("sem_init with pshared set");
44 ret = pthread_mutex_init(&sem->mutex,NULL);
45 if(ret < 0) return -1;
46 ret = pthread_cond_init(&sem->cond,NULL);
47 if(ret < 0) return -1;
51 static int sem_post(sem_t *sem) {
52 if(pthread_mutex_lock(&sem->mutex) < 0)
55 if(pthread_cond_signal(&sem->cond) < 0) {
56 pthread_mutex_unlock(&sem->mutex);
59 if(pthread_mutex_unlock(&sem->mutex) < 0)
64 static int sem_wait(sem_t *sem) {
65 if(pthread_mutex_lock(&sem->mutex) < 0)
67 while(sem->value == 0) {
68 pthread_cond_wait(&sem->cond,&sem->mutex);
71 if(pthread_mutex_unlock(&sem->mutex) < 0)
76 static int sem_destroy(sem_t *sem) {
78 ret = pthread_cond_destroy(&sem->cond);
79 if(ret < 0) return -1;
80 ret = pthread_mutex_destroy(&sem->mutex);
81 if(ret < 0) return -1;