implemented Setup.hs to build boehm cpp libs and install them;
[hs-boehmgc.git] / gc-7.2 / include / private / darwin_semaphore.h
1 /*
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.
6  * All rights reserved.
7  *
8  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
9  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
10  *
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.
16  */
17
18 #ifndef GC_DARWIN_SEMAPHORE_H
19 #define GC_DARWIN_SEMAPHORE_H
20
21 #if !defined(GC_DARWIN_THREADS)
22 #error darwin_semaphore.h included with GC_DARWIN_THREADS not defined
23 #endif
24
25 /*
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.
30 */
31
32 typedef struct {
33     pthread_mutex_t mutex;
34     pthread_cond_t cond;
35     int value;
36 } sem_t;
37
38 static int sem_init(sem_t *sem, int pshared, int value) {
39     int ret;
40     if(pshared)
41         ABORT("sem_init with pshared set");
42     sem->value = value;
43
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;
48     return 0;
49 }
50
51 static int sem_post(sem_t *sem) {
52     if(pthread_mutex_lock(&sem->mutex) < 0)
53         return -1;
54     sem->value++;
55     if(pthread_cond_signal(&sem->cond) < 0) {
56         pthread_mutex_unlock(&sem->mutex);
57         return -1;
58     }
59     if(pthread_mutex_unlock(&sem->mutex) < 0)
60         return -1;
61     return 0;
62 }
63
64 static int sem_wait(sem_t *sem) {
65     if(pthread_mutex_lock(&sem->mutex) < 0)
66         return -1;
67     while(sem->value == 0) {
68         pthread_cond_wait(&sem->cond,&sem->mutex);
69     }
70     sem->value--;
71     if(pthread_mutex_unlock(&sem->mutex) < 0)
72         return -1;
73     return 0;
74 }
75
76 static int sem_destroy(sem_t *sem) {
77     int ret;
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;
82     return 0;
83 }
84
85 #endif