-
Notifications
You must be signed in to change notification settings - Fork 0
/
semaphore.c
88 lines (76 loc) · 1.81 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <stdlib.h>
#include "semaphore.h"
#include "list.h"
#include "process.h"
/*
Semaphore
Manages semaphore system for simulation
*/
static Semaphore semaphores[SEMAPHORE_COUNT];
int Sempahore_setup() {
Semaphore * s;
for (int i = 0; i < SEMAPHORE_COUNT; i++) {
s = &semaphores[i];
s->isEnabled = false;
s->value = 0;
s->waitingList = List_create();
if (s->waitingList == NULL) {
return -1;
}
}
return 0;
}
List * Semaphore_getQueue(int sid) {
return semaphores[sid].waitingList;
}
int * Semaphore_getQueueArray(int sid) {
List * queue = Semaphore_getQueue(sid);
return Process_QueueToArray(queue);
}
bool Semaphore_isEnabled(int sid) {
return semaphores[sid].isEnabled;
}
int Semaphore_new(int sid, int svalue) {
Semaphore * s = &semaphores[sid];
if (s->isEnabled) {
return -1;
}
s->value = svalue;
s->isEnabled = true;
return sid;
}
int Semaphore_p(int sid) {
Semaphore * s = &semaphores[sid];
if (!s->isEnabled) {
return -1;
}
s->value--;
if (s->value < 0) {
PCB * process = Process_getCurrentProcess();
if (Process_isInitRunning()) {
return sid;
}
process->state = PROCESS_BLOCKED;
List_prepend(s->waitingList, process);
Process_changeRunningProcess();
}
return sid;
}
int Semaphore_v(int sid) {
Semaphore * s = &semaphores[sid];
if (!s->isEnabled) {
return -1;
}
s->value++;
if (s->value <= 0) {
PCB * process = List_trim(s->waitingList);
if (process == NULL) {
return sid;
}
Process_prependToReadyQueue(process);
if (Process_isInitRunning()) {
Process_changeRunningProcess();
}
}
return sid;
}