Updates from lab.
This commit is contained in:
parent
536fdb4aae
commit
8d38960b3f
1 changed files with 24 additions and 7 deletions
31
semaphore.h
31
semaphore.h
|
@ -45,7 +45,7 @@ private:
|
||||||
/* -- INTERNAL DATA STRUCTURES
|
/* -- INTERNAL DATA STRUCTURES
|
||||||
You may need to change them to fit your implementation. */
|
You may need to change them to fit your implementation. */
|
||||||
|
|
||||||
int value;
|
int value;
|
||||||
pthread_mutex_t m;
|
pthread_mutex_t m;
|
||||||
pthread_cond_t c;
|
pthread_cond_t c;
|
||||||
|
|
||||||
|
@ -53,26 +53,43 @@ public:
|
||||||
|
|
||||||
/* -- CONSTRUCTOR/DESTRUCTOR */
|
/* -- CONSTRUCTOR/DESTRUCTOR */
|
||||||
|
|
||||||
Semaphore(int _val){value = _val;}
|
Semaphore(int _val){
|
||||||
|
value = _val;
|
||||||
|
pthread_mutex_init(&m);
|
||||||
|
pthread_cond_init(&c);
|
||||||
|
}
|
||||||
|
|
||||||
~Semaphore(){}
|
~Semaphore(){}
|
||||||
|
|
||||||
/* -- SEMAPHORE OPERATIONS */
|
/* -- SEMAPHORE OPERATIONS */
|
||||||
|
|
||||||
int P(){
|
int P() {
|
||||||
//This is to lock the Semaphore.
|
//This is to lock the Semaphore.
|
||||||
pthread_mutex_lock( &m );
|
pthread_mutex_lock( &m );
|
||||||
|
|
||||||
//Wait until condition, basically wait until signaled.
|
--value;
|
||||||
pthread_cond_wait( &c, &m );
|
//If counter is negative, wait until condition, basically wait until signaled.
|
||||||
|
if(value < 0) {
|
||||||
|
pthread_cond_wait( &c, &m );
|
||||||
|
}
|
||||||
|
|
||||||
//Some code here.
|
//Some code here.
|
||||||
|
|
||||||
//Unlock the Semaphore.
|
//Unlock the Semaphore.
|
||||||
pthread_mutex_unlock( &m );
|
pthread_mutex_unlock( &m );
|
||||||
}
|
}
|
||||||
//;
|
//;
|
||||||
int V();
|
int V() {
|
||||||
|
pthread_mutex_lock( &m );
|
||||||
|
|
||||||
|
++value;
|
||||||
|
|
||||||
|
if(value <= 0) {
|
||||||
|
pthread_cond_signal( &c );
|
||||||
|
}
|
||||||
|
|
||||||
|
pthread_mutex_unlock( &m );
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|
Reference in a new issue