Optimize semaphore wait with zero timeout on POSIX

This commit is contained in:
sfan5 2019-11-14 17:58:07 +01:00
parent b5f5e00b29
commit 49365b25d9

@ -140,22 +140,27 @@ bool Semaphore::wait(unsigned int time_ms)
errno = EINVAL; errno = EINVAL;
} }
# else # else
struct timespec wait_time; int ret;
struct timeval now; if (time_ms > 0) {
struct timespec wait_time;
struct timeval now;
if (gettimeofday(&now, NULL) == -1) { if (gettimeofday(&now, NULL) == -1) {
std::cerr << "Semaphore::wait(ms): Unable to get time with gettimeofday!" << std::endl; std::cerr << "Semaphore::wait(ms): Unable to get time with gettimeofday!" << std::endl;
abort(); abort();
}
wait_time.tv_nsec = ((time_ms % 1000) * 1000 * 1000) + (now.tv_usec * 1000);
wait_time.tv_sec = (time_ms / 1000) + (wait_time.tv_nsec / (1000 * 1000 * 1000)) + now.tv_sec;
wait_time.tv_nsec %= 1000 * 1000 * 1000;
ret = sem_timedwait(&semaphore, &wait_time);
} else {
ret = sem_trywait(&semaphore);
} }
wait_time.tv_nsec = ((time_ms % 1000) * 1000 * 1000) + (now.tv_usec * 1000);
wait_time.tv_sec = (time_ms / 1000) + (wait_time.tv_nsec / (1000 * 1000 * 1000)) + now.tv_sec;
wait_time.tv_nsec %= 1000 * 1000 * 1000;
int ret = sem_timedwait(&semaphore, &wait_time);
# endif # endif
assert(!ret || (errno == ETIMEDOUT || errno == EINTR)); assert(!ret || (errno == ETIMEDOUT || errno == EINTR || errno == EAGAIN));
return !ret; return !ret;
#endif #endif
} }