Skip to content

Commit

Permalink
Optimize semaphore wait with zero timeout on POSIX
Browse files Browse the repository at this point in the history
  • Loading branch information
sfan5 committed Nov 14, 2019
1 parent b5f5e00 commit 49365b2
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions src/threading/semaphore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -140,22 +140,27 @@ bool Semaphore::wait(unsigned int time_ms)
errno = EINVAL;
}
# else
struct timespec wait_time;
struct timeval now;
int ret;
if (time_ms > 0) {
struct timespec wait_time;
struct timeval now;

if (gettimeofday(&now, NULL) == -1) {
std::cerr << "Semaphore::wait(ms): Unable to get time with gettimeofday!" << std::endl;
abort();
}
if (gettimeofday(&now, NULL) == -1) {
std::cerr << "Semaphore::wait(ms): Unable to get time with gettimeofday!" << std::endl;
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;
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);
ret = sem_timedwait(&semaphore, &wait_time);
} else {
ret = sem_trywait(&semaphore);
}
# endif

assert(!ret || (errno == ETIMEDOUT || errno == EINTR));
assert(!ret || (errno == ETIMEDOUT || errno == EINTR || errno == EAGAIN));
return !ret;
#endif
}
Expand Down

0 comments on commit 49365b2

Please sign in to comment.