-
Notifications
You must be signed in to change notification settings - Fork 0
/
synch.c
84 lines (72 loc) · 1.56 KB
/
synch.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//Make sure vacate does not go above original count
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "defs.h"
#include "synch.h"
#include "queue.h"
#include "minithread.h"
/*
* You must implement the procedures and types defined in this interface.
*/
/*
* Semaphores.
*/
struct semaphore {
int limit;
tas_lock_t mutex;
queue_t waiting;
};
/*
* semaphore_t semaphore_create()
* Allocate a new semaphore.
*/
semaphore_t semaphore_create() {
semaphore_t sem = (semaphore_t) malloc(sizeof(struct semaphore));
return sem;
}
/*
* semaphore_destroy(semaphore_t sem);
* Deallocate a semaphore.
*/
void semaphore_destroy(semaphore_t sem) {
queue_free(sem->waiting);
free(sem);
}
/*
* semaphore_initialize(semaphore_t sem, int cnt)
* initialize the semaphore data structure pointed at by
* sem with an initial value cnt.
*/
void semaphore_initialize(semaphore_t sem, int cnt) {
sem->limit = cnt;
sem->mutex = 0;
sem->waiting = queue_new();
}
/*
* semaphore_P(semaphore_t sem)
* Wait on the semaphore.
*/
void semaphore_P(semaphore_t sem) {
while(atomic_test_and_set(&(sem->mutex)));
if (--sem->limit < 0) {
queue_append(sem->waiting, minithread_self());
sem->mutex = 0;
minithread_stop();
} else {
sem->mutex = 0;
}
}
/*
* semaphore_V(semaphore_t sem)
* Signal on the semaphore.
*/
void semaphore_V(semaphore_t sem) {
minithread_t thread;
while(atomic_test_and_set(&(sem->mutex)));
if(++sem->limit <= 0) {
queue_dequeue(sem->waiting,(void**) &thread);
minithread_start((minithread_t) thread);
}
sem->mutex = 0;
}