This repository has been archived on 2025-04-11. You can view files and clone it, but cannot push or open issues or pull requests.
csce313-mp4pinie64backup/semaphore.h

98 lines
2.1 KiB
C
Raw Permalink Normal View History

2015-11-05 18:33:21 -06:00
/*
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>
2015-11-05 19:37:44 -06:00
//#include <mutex>
2015-11-05 18:33:21 -06:00
/*--------------------------------------------------------------------------*/
/* 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. */
2015-11-06 10:56:20 -06:00
int value;
2015-11-05 18:33:21 -06:00
pthread_mutex_t m;
pthread_cond_t c;
public:
/* -- CONSTRUCTOR/DESTRUCTOR */
2015-11-06 10:56:20 -06:00
Semaphore(int _val){
value = _val;
2015-11-06 11:30:46 -06:00
pthread_mutex_init(&m, NULL);
pthread_cond_init(&c, NULL);
2015-11-06 10:56:20 -06:00
}
2015-11-05 18:33:21 -06:00
~Semaphore(){}
/* -- SEMAPHORE OPERATIONS */
2015-11-06 10:56:20 -06:00
int P() {
2015-11-05 19:37:44 -06:00
//This is to lock the Semaphore.
pthread_mutex_lock( &m );
2015-11-06 10:56:20 -06:00
--value;
//If counter is negative, wait until condition, basically wait until signaled.
if(value < 0) {
pthread_cond_wait( &c, &m );
}
2015-11-05 19:37:44 -06:00
//Some code here.
//Unlock the Semaphore.
pthread_mutex_unlock( &m );
2015-11-06 10:56:20 -06:00
}
2015-11-05 18:33:21 -06:00
//;
2015-11-06 10:56:20 -06:00
int V() {
pthread_mutex_lock( &m );
++value;
if(value <= 0) {
pthread_cond_signal( &c );
}
pthread_mutex_unlock( &m );
}
2015-11-05 18:33:21 -06:00
};
#endif