-
Notifications
You must be signed in to change notification settings - Fork 0
/
semaphore.c
60 lines (53 loc) · 1.65 KB
/
semaphore.c
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <pthread.h>
#include <assert.h>
#include <stdlib.h>
#include "semaphore.h"
/* ********************************************************************************
How to implement the Dijsktra semaphore using some mutex and a queue
******************************************************************************** */
struct sema_state {
pthread_mutex_t mutex;
int value;
pthread_cond_t queue;
};
semaphore_t CreateSemaphore(int initial_value) {
struct sema_state *s = (struct sema_state *) malloc(sizeof(struct sema_state));
assert(s != NULL);
int ret = pthread_mutex_init(&s->mutex, NULL);
assert(ret == 0);
s->value = initial_value;
ret = pthread_cond_init(&s->queue, NULL);
assert(ret == 0);
return (semaphore_t) s;
}
void CloseSemaphore(semaphore_t sema) {
struct sema_state *s = (struct sema_state *) sema;
int ret = pthread_mutex_destroy(&s->mutex);
assert(ret == 0);
ret = pthread_cond_destroy(&s->queue);
free((char *) s);
}
void P(semaphore_t sema) {
struct sema_state *s = (struct sema_state *) sema;
int ret = pthread_mutex_lock(&s->mutex);
assert(ret == 0);
s->value--;
if (s->value < 0) {
ret = pthread_cond_wait(&s->queue, &s->mutex);
assert(ret == 0);
}
ret = pthread_mutex_unlock(&s->mutex);
assert(ret == 0);
}
void V(semaphore_t sema) {
struct sema_state *s = (struct sema_state *) sema;
int ret = pthread_mutex_lock(&s->mutex);
assert(ret == 0);
s->value++;
if (s->value <= 0) {
ret = pthread_cond_signal(&s->queue);
assert(ret == 0);
}
ret = pthread_mutex_unlock(&s->mutex);
assert(ret == 0);
}