97 lines
2.1 KiB
C++
97 lines
2.1 KiB
C++
/*
|
|
File: semaphore.H
|
|
|
|
Author: R. Bettati
|
|
Department of Computer Science
|
|
Texas A&M University
|
|
Date : 08/02/11
|
|
|
|
*/
|
|
|
|
#ifndef _semaphore_H_ // include file only once
|
|
#define _semaphore_H_
|
|
|
|
/*--------------------------------------------------------------------------*/
|
|
/* DEFINES */
|
|
/*--------------------------------------------------------------------------*/
|
|
|
|
/* -- (none) -- */
|
|
|
|
/*--------------------------------------------------------------------------*/
|
|
/* INCLUDES */
|
|
/*--------------------------------------------------------------------------*/
|
|
|
|
#include <pthread.h>
|
|
//#include <mutex>
|
|
|
|
/*--------------------------------------------------------------------------*/
|
|
/* DATA STRUCTURES */
|
|
/*--------------------------------------------------------------------------*/
|
|
|
|
/* -- (none) -- */
|
|
|
|
/*--------------------------------------------------------------------------*/
|
|
/* FORWARDS */
|
|
/*--------------------------------------------------------------------------*/
|
|
|
|
/* -- (none) -- */
|
|
|
|
/*--------------------------------------------------------------------------*/
|
|
/* CLASS S e m a p h o r e */
|
|
/*--------------------------------------------------------------------------*/
|
|
|
|
class Semaphore {
|
|
private:
|
|
/* -- INTERNAL DATA STRUCTURES
|
|
You may need to change them to fit your implementation. */
|
|
|
|
int value;
|
|
pthread_mutex_t m;
|
|
pthread_cond_t c;
|
|
|
|
public:
|
|
|
|
/* -- CONSTRUCTOR/DESTRUCTOR */
|
|
|
|
Semaphore(int _val){
|
|
value = _val;
|
|
pthread_mutex_init(&m, NULL);
|
|
pthread_cond_init(&c, NULL);
|
|
}
|
|
|
|
~Semaphore(){}
|
|
|
|
/* -- SEMAPHORE OPERATIONS */
|
|
|
|
int P() {
|
|
//This is to lock the Semaphore.
|
|
pthread_mutex_lock( &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() {
|
|
pthread_mutex_lock( &m );
|
|
|
|
++value;
|
|
|
|
if(value <= 0) {
|
|
pthread_cond_signal( &c );
|
|
}
|
|
|
|
pthread_mutex_unlock( &m );
|
|
}
|
|
};
|
|
|
|
#endif
|
|
|
|
|