#include "SDL_internal.h"
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include "SDL_sysmutex_c.h"
struct SDL_Condition
{
pthread_cond_t cond;
};
SDL_Condition *SDL_CreateCondition(void)
{
SDL_Condition *cond;
cond = (SDL_Condition *)SDL_malloc(sizeof(SDL_Condition));
if (cond) {
if (pthread_cond_init(&cond->cond, NULL) != 0) {
SDL_SetError("pthread_cond_init() failed");
SDL_free(cond);
cond = NULL;
}
}
return cond;
}
void SDL_DestroyCondition(SDL_Condition *cond)
{
if (cond) {
pthread_cond_destroy(&cond->cond);
SDL_free(cond);
}
}
void SDL_SignalCondition(SDL_Condition *cond)
{
if (!cond) {
return;
}
pthread_cond_signal(&cond->cond);
}
void SDL_BroadcastCondition(SDL_Condition *cond)
{
if (!cond) {
return;
}
pthread_cond_broadcast(&cond->cond);
}
bool SDL_WaitConditionTimeoutNS(SDL_Condition *cond, SDL_Mutex *mutex, Sint64 timeoutNS)
{
#ifndef HAVE_CLOCK_GETTIME
struct timeval delta;
#endif
struct timespec abstime;
if (!cond || !mutex) {
return true;
}
if (timeoutNS < 0) {
return (pthread_cond_wait(&cond->cond, &mutex->id) == 0);
}
#ifdef HAVE_CLOCK_GETTIME
clock_gettime(CLOCK_REALTIME, &abstime);
abstime.tv_sec += (timeoutNS / SDL_NS_PER_SECOND);
abstime.tv_nsec += (timeoutNS % SDL_NS_PER_SECOND);
#else
gettimeofday(&delta, NULL);
abstime.tv_sec = delta.tv_sec + (timeoutNS / SDL_NS_PER_SECOND);
abstime.tv_nsec = SDL_US_TO_NS(delta.tv_usec) + (timeoutNS % SDL_NS_PER_SECOND);
#endif
while (abstime.tv_nsec >= 1000000000) {
abstime.tv_sec += 1;
abstime.tv_nsec -= 1000000000;
}
bool result;
int rc;
tryagain:
rc = pthread_cond_timedwait(&cond->cond, &mutex->id, &abstime);
switch (rc) {
case EINTR:
goto tryagain;
case ETIMEDOUT:
result = false;
break;
default:
result = true;
break;
}
return result;
}