From 8d38960b3f4f51a671706177a8b6ad1a8887b555 Mon Sep 17 00:00:00 2001 From: shadow8t4 Date: Fri, 6 Nov 2015 10:56:20 -0600 Subject: [PATCH] Updates from lab. --- semaphore.h | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/semaphore.h b/semaphore.h index 6b9649c..25df369 100755 --- a/semaphore.h +++ b/semaphore.h @@ -45,7 +45,7 @@ private: /* -- INTERNAL DATA STRUCTURES You may need to change them to fit your implementation. */ - int value; + int value; pthread_mutex_t m; pthread_cond_t c; @@ -53,26 +53,43 @@ public: /* -- CONSTRUCTOR/DESTRUCTOR */ - Semaphore(int _val){value = _val;} + Semaphore(int _val){ + value = _val; + pthread_mutex_init(&m); + pthread_cond_init(&c); + } ~Semaphore(){} /* -- SEMAPHORE OPERATIONS */ - int P(){ + int P() { //This is to lock the Semaphore. pthread_mutex_lock( &m ); - //Wait until condition, basically wait until signaled. - pthread_cond_wait( &c, &m ); + --value; + //If counter is negative, wait until condition, basically wait until signaled. + if(value < 0) { + pthread_cond_wait( &c, &m ); + } //Some code here. //Unlock the Semaphore. pthread_mutex_unlock( &m ); - } + } //; - int V(); + int V() { + pthread_mutex_lock( &m ); + + ++value; + + if(value <= 0) { + pthread_cond_signal( &c ); + } + + pthread_mutex_unlock( &m ); + } }; /*