-
Notifications
You must be signed in to change notification settings - Fork 2
/
sem.h
52 lines (39 loc) · 1.09 KB
/
sem.h
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
//
// Created by connor on 4/6/15.
//
#ifndef _CSE340_PROJECT_3_SEM_H_
#define _CSE340_PROJECT_3_SEM_H_
#include <stdio.h>
#include <stdlib.h>
#include "threads.h"
#include "q.h"
struct Semaphore {
int value;
struct Queue* queue;
};
struct Semaphore* newSemaphore(int initial_value) {
struct Semaphore* new_semaphore = malloc(sizeof(struct Semaphore));
new_semaphore->value = initial_value;
new_semaphore->queue = newQueue();
return new_semaphore;
}
void P(struct Semaphore* semaphore) {
semaphore->value--;
// move a task from the run queue to this queue
if (semaphore->value < 0) {
TCB_t *task_to_block = (TCB_t *) dequeue(run_queue, FALSE);
if (task_to_block != NULL)
enqueue(semaphore->queue, task_to_block);
yield();
}
}
void V(struct Semaphore* semaphore) {
semaphore->value++;
if (semaphore->value <= 0) {
TCB_t *task_to_run = (TCB_t *) dequeue(semaphore->queue, FALSE);
if (task_to_run != NULL)
enqueue(run_queue, task_to_run);
}
yield();
}
#endif //_CSE340_PROJECT_3_SEM_H_