-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSemaphore.cpp
More file actions
33 lines (27 loc) · 804 Bytes
/
Semaphore.cpp
File metadata and controls
33 lines (27 loc) · 804 Bytes
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
#include "Semaphore.hpp"
Semaphore::Semaphore(unsigned val) {
pthread_mutex_init(&global_lock,NULL);
pthread_cond_init(¬_empty,NULL);
cnt=val;
}
Semaphore::~Semaphore() {
pthread_mutex_destroy(&global_lock);
pthread_cond_destroy(¬_empty);
}
void Semaphore::up() {
pthread_mutex_lock(&global_lock);
cnt++;
//cout << "Cnt: " << cnt << endl;
pthread_cond_signal(¬_empty);
pthread_mutex_unlock(&global_lock);
}
void Semaphore::down() {
pthread_mutex_lock(&global_lock);
//int* pid = (int*)pthread_self().p;
while(cnt==0){
//cout << pthread_self() << " can't join the party yet. " << endl;
pthread_cond_wait(¬_empty,&global_lock);
}
cnt--;
pthread_mutex_unlock(&global_lock);
}