Universidad de Costa Rica

Escuela de Ciencias de la Computación e Informática

CI-0117 Programación paralela y concurrente

Prácticas

CI0117 / Practicas / Semana-02


/**
 *  C++ class to encapsulate Unix semaphore intrinsic structures and system calls
 *  Author: Programacion Concurrente (Francisco Arroyo)
 *  Version: 2025/Ago/18
 *
 * Ref.: https://en.wikipedia.org/wiki/Semaphore_(programming)
 *
 **/

#include <stdexcept>            // runtime_error

#include "Semaforo.h"

/**
  * Class constructor
  *    Build a operating system semaphore set, using semget
  *    Could provide a initial value using semctl, if not it will be zero
  *
 **/
Semaforo::Semaforo( int valorInicial ) {
   int resultado = -1;
// Use semget to create a System V semaphore set identifier
// Use semctl to state a initial value to semaphore set

   if ( -1 == resultado ) {
      throw std::runtime_error( "Semaforo::Semaforo( int )" );
   }

}


/**
  * Class destructor
  *    Destroy a semaphore set identifier, using semctl
  *
 **/
Semaforo::~Semaforo() {
// Use semctl to destroy a semaphore set identifier
}


/**
  * Signal method 
  *    Add 1 to sempahore value, check if are waiting process and awake first one
  *
 **/
int Semaforo::Signal() {
   int resultado = -1;

// Use semop
   if ( -1 == resultado ) {
      throw std::runtime_error( "Semaforo::Signal()" );
   }

   return resultado;

}


/**
  * Signal method 
  *    Substract 1 to sempahore value, check if negative or zero, calling process will sleep
  *    and wait for next Signal operation
  *
 **/
int Semaforo::Wait() {
   int resultado = -1;
   struct sembuf wait;

// Use semop
   if ( -1 == resultado ) {
      throw std::runtime_error( "Semaforo::Signal()" );
   }

   return resultado;

}