/**
* This class encapsulates condition variables functionality
*
* Autor: Sistemas Operativos (Francisco Arroyo)
*
* Fecha: 2023/Abr/23
*
**/
#include "Condition.h"
/**
* Creates a new condition variable
*
* Uses an internal structure to make workers wait for resources
*
**/
Condition::Condition() {
this->waitingWorkers = 0;
this->internalWaitMechanism = new Lock();
}
/**
* Destroys our condition variable
**/
Condition::~Condition() {
delete this->internalWaitMechanism;
}
/**
* Wait for the condition controlled by our variable
*
**/
void Condition::Wait( Lock & affectedLock ) {
this->waitingWorkers++;
affectedLock.Release();
this->internalWaitMechanism->Acquire();
affectedLock.Acquire();
}
/**
* Notify one worker from the queue, if empty has no effect
*
**/
void Condition::NotifyOne() {
if ( this->waitingWorkers > 0 ) {
this->waitingWorkers--; // One
this->internalWaitMechanism->Release();
}
}
/**
* Same method as notify one, declared for compatibility with many examples
*
**/
void Condition::Signal() {
this->NotifyOne();
}
/**
* Signal all workers from the queue, if empty has no effect
*
**/
void Condition::NotifyAll() {
while ( this->waitingWorkers > 0 ) {
this->waitingWorkers--;
this->internalWaitMechanism->Release();
}
}