/*******************************************************************************
 *	BCond.cc	BCond Classes
 *			T.Barnaby,	BEAM Ltd,	15/11/02
 *******************************************************************************
 */
#include <BCond.h>
#include <sys/time.h>
#include <stdio.h>

BCond::BCond(){
	pthread_mutex_init(&omutex, 0);
	pthread_cond_init(&ocond, 0);
}

BCond::~BCond(){
	pthread_cond_destroy(&ocond);
	pthread_mutex_destroy(&omutex);
}

int BCond::signal(){
	return pthread_cond_broadcast(&ocond);
}

int BCond::wait(){
	int	ret;
	
	pthread_mutex_lock(&omutex);
	ret = pthread_cond_wait(&ocond, &omutex);
	pthread_mutex_unlock(&omutex);
	return ret;
}

int BCond::timedWait(int timeOutUs){
	int		ret;
	struct timeval	tv;
	struct timespec	ts;
	
	gettimeofday(&tv, 0);
	ts.tv_sec = tv.tv_sec + timeOutUs / 1000000;
	ts.tv_nsec = (tv.tv_usec + timeOutUs % 1000000) * 1000;
	ts.tv_sec += (ts.tv_nsec / 1000000000);
	ts.tv_nsec %=  1000000000;
	
	pthread_mutex_lock(&omutex);
	ret = pthread_cond_timedwait(&ocond, &omutex, &ts);
	pthread_mutex_unlock(&omutex);
	return ret;
}
