| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
#include <stdlib.h> |
| 28 |
|
| 29 |
#include <rthreads/rthreads.h> |
| 30 |
#include <rthreads/rsemaphore.h> |
| 31 |
|
| 32 |
struct ssem |
| 33 |
{ |
| 34 |
int value; |
| 35 |
int wakeups; |
| 36 |
slock_t *mutex; |
| 37 |
scond_t *cond; |
| 38 |
}; |
| 39 |
|
| 40 |
ssem_t *ssem_new(int value) |
| 41 |
{ |
| 42 |
ssem_t *semaphore = (ssem_t*)calloc(1, sizeof(*semaphore)); |
| 43 |
|
| 44 |
if (!semaphore) |
| 45 |
goto error; |
| 46 |
|
| 47 |
semaphore->value = value; |
| 48 |
semaphore->wakeups = 0; |
| 49 |
semaphore->mutex = slock_new(); |
| 50 |
|
| 51 |
if (!semaphore->mutex) |
| 52 |
goto error; |
| 53 |
|
| 54 |
semaphore->cond = scond_new(); |
| 55 |
|
| 56 |
if (!semaphore->cond) |
| 57 |
goto error; |
| 58 |
|
| 59 |
return semaphore; |
| 60 |
|
| 61 |
error: |
| 62 |
if (semaphore->mutex) |
| 63 |
slock_free(semaphore->mutex); |
| 64 |
semaphore->mutex = NULL; |
| 65 |
if (semaphore) |
| 66 |
free((void*)semaphore); |
| 67 |
return NULL; |
| 68 |
} |
| 69 |
|
| 70 |
void ssem_free(ssem_t *semaphore) |
| 71 |
{ |
| 72 |
if (!semaphore) |
| 73 |
return; |
| 74 |
|
| 75 |
scond_free(semaphore->cond); |
| 76 |
slock_free(semaphore->mutex); |
| 77 |
free((void*)semaphore); |
| 78 |
} |
| 79 |
|
| 80 |
void ssem_wait(ssem_t *semaphore) |
| 81 |
{ |
| 82 |
if (!semaphore) |
| 83 |
return; |
| 84 |
|
| 85 |
slock_lock(semaphore->mutex); |
| 86 |
semaphore->value--; |
| 87 |
|
| 88 |
if (semaphore->value < 0) |
| 89 |
{ |
| 90 |
do |
| 91 |
{ |
| 92 |
scond_wait(semaphore->cond, semaphore->mutex); |
| 93 |
}while (semaphore->wakeups < 1); |
| 94 |
|
| 95 |
semaphore->wakeups--; |
| 96 |
} |
| 97 |
|
| 98 |
slock_unlock(semaphore->mutex); |
| 99 |
} |
| 100 |
|
| 101 |
void ssem_signal(ssem_t *semaphore) |
| 102 |
{ |
| 103 |
if (!semaphore) |
| 104 |
return; |
| 105 |
|
| 106 |
slock_lock(semaphore->mutex); |
| 107 |
semaphore->value++; |
| 108 |
|
| 109 |
if (semaphore->value <= 0) |
| 110 |
{ |
| 111 |
semaphore->wakeups++; |
| 112 |
scond_signal(semaphore->cond); |
| 113 |
} |
| 114 |
|
| 115 |
slock_unlock(semaphore->mutex); |
| 116 |
} |