Debian Codegraph @

external/bdwgc/include/private/darwin_semaphore.h

raw
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 #ifdef __cplusplus
26 extern "C" {
27 #endif
28
29 /* This is a very simple semaphore implementation for Darwin. It is */
30 /* implemented in terms of pthread calls so it is not async signal */
31 /* safe. But this is not a problem because signals are not used to */
32 /* suspend threads on Darwin. */
33
34 typedef struct {
35 pthread_mutex_t mutex;
36 pthread_cond_t cond;
37 int value;
38 } sem_t;
39
40 GC_INLINE int sem_init(sem_t *sem, int pshared, int value) {
41 if (pshared != 0) {
42 errno = EPERM; /* unsupported */
43 return -1;
44 }
45 sem->value = value;
46 if (pthread_mutex_init(&sem->mutex, NULL) != 0)
47 return -1;
48 if (pthread_cond_init(&sem->cond, NULL) != 0) {
49 (void)pthread_mutex_destroy(&sem->mutex);
50 return -1;
51 }
52 return 0;
53 }
54
55 GC_INLINE int sem_post(sem_t *sem) {
56 if (pthread_mutex_lock(&sem->mutex) != 0)
57 return -1;
58 sem->value++;
59 if (pthread_cond_signal(&sem->cond) != 0) {
60 (void)pthread_mutex_unlock(&sem->mutex);
61 return -1;
62 }
63 return pthread_mutex_unlock(&sem->mutex) != 0 ? -1 : 0;
64 }
65
66 GC_INLINE int sem_wait(sem_t *sem) {
67 if (pthread_mutex_lock(&sem->mutex) != 0)
68 return -1;
69 while (sem->value == 0) {
70 if (pthread_cond_wait(&sem->cond, &sem->mutex) != 0) {
71 (void)pthread_mutex_unlock(&sem->mutex);
72 return -1;
73 }
74 }
75 sem->value--;
76 return pthread_mutex_unlock(&sem->mutex) != 0 ? -1 : 0;
77 }
78
79 GC_INLINE int sem_destroy(sem_t *sem) {
80 return pthread_cond_destroy(&sem->cond) != 0
81 || pthread_mutex_destroy(&sem->mutex) != 0 ? -1 : 0;
82 }
83
84 #ifdef __cplusplus
85 } /* extern "C" */
86 #endif
87
88 #endif