286
|
1 #include "../context.h"
|
|
2
|
|
3 Semaphore* createSemaphoreImpl(struct Context* context, int n) {
|
|
4 struct Semaphore* semaphore = new Semaphore();
|
|
5 struct SemaphoreImpl* semaphoreImpl = new SemaphoreImpl();
|
|
6 semaphore->semaphore = (union Data*)semaphoreImpl;
|
|
7 semaphoreImpl->value = n;
|
|
8 pthread_mutex_init(&semaphoreImpl->mutex, NULL);
|
|
9 pthread_cond_init(&semaphoreImpl->cond, NULL);
|
|
10 semaphore->p = C_pOperationSemaphoreImpl;
|
|
11 semaphore->v = C_vOperationSemaphoreImpl;
|
|
12 return semaphore;
|
|
13 }
|
|
14
|
|
15 __code pOperationSemaphoreImpl(struct SemaphoreImpl* semaphore, __code next(...)) {
|
|
16 pthread_mutex_lock(&semaphore->mutex);
|
|
17 goto meta(context, C_pOperationSemaphoreImpl1);
|
|
18 }
|
|
19
|
|
20 __code pOperationSemaphoreImpl1(struct SemaphoreImpl* semaphore, __code next(...)) {
|
|
21 if(semaphore->value == 0) {
|
|
22 pthread_cond_wait(&semaphore->cond, &semaphore->mutex);
|
|
23 goto meta(context, C_pOperationSemaphoreImpl1);
|
|
24 }
|
|
25 semaphore->value--;
|
|
26 pthread_mutex_unlock(&semaphore->mutex);
|
|
27 goto next(...);
|
|
28 }
|
|
29
|
|
30 __code vOperationSemaphoreImpl(struct SemaphoreImpl* semaphore, __code next(...)) {
|
|
31 pthread_mutex_lock(&semaphore->mutex);
|
|
32 semaphore->value++;
|
|
33 pthread_cond_signal(&semaphore->cond);
|
|
34 pthread_mutex_unlock(&semaphore->mutex);
|
|
35 goto next(...);
|
|
36 }
|