-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSemaphore.cpp
52 lines (42 loc) · 896 Bytes
/
Semaphore.cpp
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 tim on 10/28/19.
//
#include "Semaphore.h"
Semaphore::Semaphore(){
}
Semaphore::Semaphore(pthread_mutex_t * mutex_in, int count){
total_count = count;
cur_count = total_count;
mutex = mutex_in;
pthread_mutex_init(mutex, NULL);
}
int Semaphore::getCount(){
return total_count - cur_count;
}
Semaphore::~Semaphore(){
pthread_mutex_destroy(mutex);
}
void Semaphore::init(pthread_mutex_t * mutex_in, int count){
total_count = count;
cur_count = total_count;
mutex = mutex_in;
pthread_mutex_init(mutex, NULL);
}
void Semaphore::wait(){
if(cur_count > 0){
cur_count--;
}
if(cur_count == 0){
pthread_mutex_lock(mutex);
}
}
void Semaphore::signal(){
bool unlock = false;
if(cur_count == 0){
unlock = true;
}
cur_count++;
if(unlock){
pthread_mutex_unlock(mutex);
}
}