DSEventSemaphore.cpp [plain text]
#include <errno.h>
#include <sys/time.h> // for struct timespec and gettimeofday();
#include "DSEventSemaphore.h"
DSEventSemaphore::DSEventSemaphore( void )
{
fbEvent = false;
fMilliSecsTotal = 0;
pthread_mutex_init( &fMutex, NULL );
pthread_cond_init( &fCondition, NULL );
}
DSEventSemaphore::~DSEventSemaphore( void )
{
pthread_mutex_destroy( &fMutex );
pthread_cond_destroy( &fCondition );
}
bool DSEventSemaphore::WaitForEvent( SInt32 milliSecs )
{
pthread_mutex_lock( &fMutex );
if( fbEvent == false )
{
if( milliSecs == 0 ) {
pthread_cond_wait( &fCondition, &fMutex );
}
else if( milliSecs > 0 )
{
if (fMilliSecsTotal >= milliSecs)
{
pthread_mutex_unlock( &fMutex );
return false;
}
else
{
struct timeval tvNow;
struct timespec tsTimeout;
gettimeofday( &tvNow, NULL );
TIMEVAL_TO_TIMESPEC ( &tvNow, &tsTimeout );
tsTimeout.tv_sec += (milliSecs / 1000);
tsTimeout.tv_nsec += ((milliSecs % 1000) * 1000000);
if( pthread_cond_timedwait(&fCondition, &fMutex, &tsTimeout) == ETIMEDOUT )
{
bool bReturn = fbEvent;
fMilliSecsTotal += milliSecs; pthread_mutex_unlock( &fMutex );
return bReturn;
}
}
}
}
pthread_mutex_unlock( &fMutex );
return true;
}
void DSEventSemaphore::PostEvent( void )
{
pthread_mutex_lock( &fMutex );
fbEvent = true;
pthread_cond_broadcast( &fCondition );
pthread_mutex_unlock( &fMutex );
}
void DSEventSemaphore::ResetEvent( void )
{
pthread_mutex_lock( &fMutex );
fbEvent = false;
fMilliSecsTotal = 0;
pthread_mutex_unlock( &fMutex );
}