-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSemaphore.cpp
More file actions
46 lines (43 loc) · 1.18 KB
/
Semaphore.cpp
File metadata and controls
46 lines (43 loc) · 1.18 KB
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
#include "Semaphore.hpp"
Semaphore::Semaphore(): val(0) {
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
}
Semaphore::Semaphore(unsigned val):
val(val) {
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
}
Semaphore::Semaphore(int val):
val(val) {
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
}
Semaphore::~Semaphore(){
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&lock);
}
void Semaphore::down(){ //Wait
pthread_mutex_lock(&lock);
while(val <= 0) {
pthread_cond_wait(&cond,&lock);
}
--val;
pthread_mutex_unlock(&lock);
} // Block untill counter >0, and mark - One thread has entered the critical section.
void Semaphore::up(){ //Signal
pthread_mutex_lock(&lock);
++val;
pthread_mutex_unlock(&lock);
pthread_cond_broadcast(&cond);
} // Mark: 1 Thread has left the critical section
void Semaphore::up(int delta){ //Signal
pthread_mutex_lock(&lock);
val+=delta;
pthread_mutex_unlock(&lock);
for(int i = 0; i < delta; i++)
pthread_cond_signal(&cond);
} // Mark: 1 Thread has left the critical section
int Semaphore::get_val(){
return val;
}