-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsem.h
66 lines (53 loc) · 1.62 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//
// Created by student on 10/23/16.
//
#include "threads.h"
#ifndef CSE330PROJECT_SEM_H
#define CSE330PROJECT_SEM_H
//structure to define semaphores
typedef struct sem_t
{
int val; //value of the semaphore
TCB_t* queue; //queue of threads waiting on this semaphore
} sem_t;
// Initializes the value field with the specified value.
void InitSem(sem_t* sem, int val)
{
//set the value of the parameter semaphore to the parameter value
sem->val = val;
sem->queue = newQueue();
}
//decrements the semaphore, and if the value is less than zero
//then blocks the thread in the queue associated with the semaphore
void P(sem_t* sem)
{
//decrement the semaphore
sem->val--;
// if the value is LTE zero, block the thread
if(sem->val < 0)
{
//add the current thread to the semaphore queue
AddQueue(sem->queue, Curr_Thread);
//store the current thread for context switch
struct TCB_t* Prev_Thread = Curr_Thread;
//get the next thread from the ready queue
Curr_Thread = DelQueue(ReadyQ);
//swap context to next thread
swapcontext(&(Prev_Thread->context), &(Curr_Thread->context));
}
}
//Increments the semaphore, and if the value is 0 or negative,
//then takes a PCB out of the semaphore queue and puts it into the ReadyQ queue.
void V(sem_t* sem)
{
//increment the semaphore
sem->val++;
//if value is less than or equal to zero, add the next thread to the ready queue
if(sem->val <= 0)
{
AddQueue(ReadyQ, DelQueue(sem->queue));
}
//yield to the next thread
yield();
}
#endif //CSE330PROJECT_SEM_H