forked from MAYHEM-Lab/cspot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsema.c
69 lines (54 loc) · 842 Bytes
/
sema.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
61
62
63
64
65
66
67
68
69
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include "sema.h"
int InitSem(sema *s, int count)
{
if (s == NULL)
{
return (-1);
}
s->value = count;
s->waiters = 0;
pthread_cond_init(&(s->wait), NULL);
pthread_mutex_init(&(s->lock), NULL);
return (1);
}
void FreeSem(sema *s)
{
free(s);
}
void P(sema *s)
{
pthread_mutex_lock(&(s->lock));
s->value--;
while (s->value < 0)
{
/*
* maintain semaphore invariant
*/
if (s->waiters < (-1 * s->value))
{
s->waiters++;
pthread_cond_wait(&(s->wait), &(s->lock));
s->waiters--;
}
else
{
break;
}
}
pthread_mutex_unlock(&(s->lock));
return;
}
void V(sema *s)
{
pthread_mutex_lock(&(s->lock));
s->value++;
if (s->value <= 0)
{
pthread_cond_signal(&(s->wait));
}
pthread_mutex_unlock(&(s->lock));
}