| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
#include "asterisk.h" |
| 25 |
|
| 26 |
#include "asterisk/sem.h" |
| 27 |
#include "asterisk/utils.h" |
| 28 |
|
| 29 |
#ifndef HAS_WORKING_SEMAPHORE |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
int ast_sem_init(struct ast_sem *sem, int pshared, unsigned int value) |
| 34 |
{ |
| 35 |
if (pshared) { |
| 36 |
|
| 37 |
errno = ENOSYS; |
| 38 |
return -1; |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
if (value > AST_SEM_VALUE_MAX) { |
| 44 |
errno = EINVAL; |
| 45 |
return -1; |
| 46 |
} |
| 47 |
|
| 48 |
sem->count = value; |
| 49 |
sem->waiters = 0; |
| 50 |
ast_mutex_init(&sem->mutex); |
| 51 |
ast_cond_init(&sem->cond, NULL); |
| 52 |
return 0; |
| 53 |
} |
| 54 |
|
| 55 |
int ast_sem_destroy(struct ast_sem *sem) |
| 56 |
{ |
| 57 |
ast_mutex_destroy(&sem->mutex); |
| 58 |
ast_cond_destroy(&sem->cond); |
| 59 |
return 0; |
| 60 |
} |
| 61 |
|
| 62 |
int ast_sem_post(struct ast_sem *sem) |
| 63 |
{ |
| 64 |
SCOPED_MUTEX(lock, &sem->mutex); |
| 65 |
|
| 66 |
ast_assert(sem->count >= 0); |
| 67 |
|
| 68 |
if (sem->count == AST_SEM_VALUE_MAX) { |
| 69 |
errno = EOVERFLOW; |
| 70 |
return -1; |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
++sem->count; |
| 75 |
|
| 76 |
|
| 77 |
if (sem->waiters) { |
| 78 |
ast_cond_signal(&sem->cond); |
| 79 |
} |
| 80 |
|
| 81 |
return 0; |
| 82 |
} |
| 83 |
|
| 84 |
int ast_sem_wait(struct ast_sem *sem) |
| 85 |
{ |
| 86 |
int res; |
| 87 |
SCOPED_MUTEX(lock, &sem->mutex); |
| 88 |
|
| 89 |
ast_assert(sem->count >= 0); |
| 90 |
|
| 91 |
|
| 92 |
++sem->waiters; |
| 93 |
while (sem->count == 0) { |
| 94 |
res = ast_cond_wait(&sem->cond, &sem->mutex); |
| 95 |
|
| 96 |
if (res != 0) { |
| 97 |
--sem->waiters; |
| 98 |
return res; |
| 99 |
} |
| 100 |
} |
| 101 |
--sem->waiters; |
| 102 |
|
| 103 |
|
| 104 |
--sem->count; |
| 105 |
|
| 106 |
return 0; |
| 107 |
} |
| 108 |
|
| 109 |
int ast_sem_timedwait(struct ast_sem *sem, const struct timespec *abs_timeout) |
| 110 |
{ |
| 111 |
int res; |
| 112 |
SCOPED_MUTEX(lock, &sem->mutex); |
| 113 |
|
| 114 |
ast_assert(sem->count >= 0); |
| 115 |
|
| 116 |
|
| 117 |
++sem->waiters; |
| 118 |
while (sem->count == 0) { |
| 119 |
res = ast_cond_timedwait(&sem->cond, &sem->mutex, abs_timeout); |
| 120 |
|
| 121 |
if (res != 0) { |
| 122 |
--sem->waiters; |
| 123 |
return res; |
| 124 |
} |
| 125 |
} |
| 126 |
--sem->waiters; |
| 127 |
|
| 128 |
|
| 129 |
--sem->count; |
| 130 |
|
| 131 |
return 0; |
| 132 |
} |
| 133 |
|
| 134 |
int ast_sem_getvalue(struct ast_sem *sem, int *sval) |
| 135 |
{ |
| 136 |
SCOPED_MUTEX(lock, &sem->mutex); |
| 137 |
|
| 138 |
ast_assert(sem->count >= 0); |
| 139 |
|
| 140 |
*sval = sem->count; |
| 141 |
|
| 142 |
return 0; |
| 143 |
} |
| 144 |
|
| 145 |
#endif |