/** * C++ class to encapsulate Unix semaphore intrinsic structures and system calls * Author: Programacion Concurrente (Francisco Arroyo) * Version: 2020/Ago/04 * * En esta nueva versión vamos a construir un arreglo de semáforos, * el tamaño es indicado por el constructor (cantidad) * Las operaciones Wait y Signal reciben el parámetro sobre el cual se pretende * realizar esa operación * Además, vamos a agregar dos métodos nuevos para poder operar sobre dos * semáforos simultáneamente y resolver el problema de los filósofos * **/ #include #include #include #include "Sem.h" /** * sem_init **/ Sem::Sem( int initial ) { int rs; this->semId = (sem_t *) calloc( 1, sizeof( sem_t ) ); rs = sem_init( this->semId, 0, initial ); if ( -1 == rs ) { perror( "Sem::Sem" ); exit( 1 ); } } /** * sem_destroy **/ Sem::~Sem() { int rs; rs = sem_destroy( this->semId ); if ( -1 == rs ) { perror( "Sem::Sem" ); exit( 1 ); } free( this->semId ); } /** * sem_post **/ int Sem::Signal() { int rs; rs = sem_post( this->semId ); if ( -1 == rs ) { perror( "Sem::Signal" ); exit( 1 ); } return rs; } /** * sem_wait **/ int Sem::Wait() { int rs; rs = sem_wait( this->semId ); if ( -1 == rs ) { perror( "Sem::Wait" ); exit( 1 ); } return rs; } /* * sem_trywait */ int Sem::tryWait() { int rs; rs = sem_trywait( this->semId ); if ( -1 == rs ) { perror( "Sem::tryWait" ); exit( 1 ); } return rs; } /* * sem_timedwait */ int Sem::timedWait( long sec, long nsec ) { int rs; struct timespec lapse; lapse.tv_nsec = nsec; lapse.tv_sec = sec; rs = sem_timedwait( this->semId, & lapse ); if ( -1 == rs ) { perror( "Sem::timedWait" ); exit( 1 ); } return rs; }