1 #ifndef GC_DARWIN_SEMAPHORE_H
2 #define GC_DARWIN_SEMAPHORE_H
4 #if !defined(GC_DARWIN_THREADS)
5 #error darwin_semaphore.h included with GC_DARWIN_THREADS not defined
9 This is a very simple semaphore implementation for darwin. It
10 is implemented in terms of pthreads calls so it isn't async signal
11 safe. This isn't a problem because signals aren't used to
12 suspend threads on darwin.
16 pthread_mutex_t mutex
;
21 static int sem_init(sem_t
*sem
, int pshared
, int value
) {
24 GC_abort("sem_init with pshared set");
27 ret
= pthread_mutex_init(&sem
->mutex
,NULL
);
28 if(ret
< 0) return -1;
29 ret
= pthread_cond_init(&sem
->cond
,NULL
);
30 if(ret
< 0) return -1;
34 static int sem_post(sem_t
*sem
) {
35 if(pthread_mutex_lock(&sem
->mutex
) < 0)
38 if(pthread_cond_signal(&sem
->cond
) < 0) {
39 pthread_mutex_unlock(&sem
->mutex
);
42 if(pthread_mutex_unlock(&sem
->mutex
) < 0)
47 static int sem_wait(sem_t
*sem
) {
48 if(pthread_mutex_lock(&sem
->mutex
) < 0)
50 while(sem
->value
== 0) {
51 pthread_cond_wait(&sem
->cond
,&sem
->mutex
);
54 if(pthread_mutex_unlock(&sem
->mutex
) < 0)
59 static int sem_destroy(sem_t
*sem
) {
61 ret
= pthread_cond_destroy(&sem
->cond
);
62 if(ret
< 0) return -1;
63 ret
= pthread_mutex_destroy(&sem
->mutex
);
64 if(ret
< 0) return -1;