-
Notifications
You must be signed in to change notification settings - Fork 1
/
sem.h
29 lines (27 loc) · 814 Bytes
/
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
#include<pthread.h>
struct semaphore{
int value;
pthread_cond_t ConditionVar;
pthread_mutex_t MutexVar;
};
void create(struct semaphore* sem,int input){
sem->value=input;
sem->ConditionVar=(pthread_cond_t)PTHREAD_COND_INITIALIZER;
sem->MutexVar=(pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
}
void wait(struct semaphore* sem){
pthread_mutex_lock(&(sem->MutexVar));
sem->value--;
if(sem->value<0){
pthread_cond_wait(&(sem->ConditionVar),&(sem->MutexVar));
}
pthread_mutex_unlock(&(sem->MutexVar));
}
void signal(struct semaphore* sem){
pthread_mutex_lock(&(sem->MutexVar));
sem->value++;
if(sem->value<=0){
pthread_cond_signal(&(sem->ConditionVar));
}
pthread_mutex_unlock(&(sem->MutexVar));
}