Skip to content

Instantly share code, notes, and snippets.

@mu578
Created December 10, 2020 19:25
Show Gist options
  • Save mu578/4fb8bab6db66e79b88f1d774f6ac58f7 to your computer and use it in GitHub Desktop.
Save mu578/4fb8bab6db66e79b88f1d774f6ac58f7 to your computer and use it in GitHub Desktop.
pthread_cond_timedwait example
static inline
void timeval_to_timespec(const struct timeval * tv, struct timespec * ts)
{
ts->tv_sec = tv->tv_sec;
ts->tv_nsec = tv->tv_usec * 1000;
}
static inline
void timespec_to_timeval(const struct timespec * ts, struct timeval * tv)
{
tv->tv_sec = ts->tv_sec;
tv->tv_usec = ts->tv_nsec / 1000;
}
static inline
void timespec_now(struct timespec * ts)
{
# if HAVE_CLOCK_GETTIME
if (clock_gettime(CLOCK_REALTIME, ts) < 0) {
ts->tv_sec = -1;
ts->tv_nsec = -1;
}
# elif HAVE_GETTIMEOFDAY
struct timeval tv;
gettimeofday(&tv, NULL);
timeval_to_timespec(tv, ts);
# else
ts->tv_sec = 0;
ts->tv_nsec = 0;
# endif
}
static inline
unsigned long timespec_to_nanoseconds(const struct timespec * ts)
{
return (unsigned long)ts->tv_sec * 1000000000UL + (unsigned long)ts->tv_nsec;
}
static inline
void nanoseconds_to_timespec(unsigned long nanoseconds, struct timespec * ts)
{
ts->tv_sec = (nanoseconds / 1000000000UL);
ts->tv_nsec = (nanoseconds % 1000000000UL);
}
static inline
void add_nanoseconds_to_timespec(unsigned long nanoseconds, struct timespec * ts)
{
ts->tv_sec += (nanoseconds / 1000000000UL);
ts->tv_nsec += (nanoseconds % 1000000000UL);
}
static inline
int pthread_cond_timedwait_nanoseconds(
pthread_cond_t * restrict cond
, pthread_mutex_t * restrict mutex
, unsigned long nanoseconds
) {
struct timespec abstime;
timespec_now(&abstime);
add_nanoseconds_to_timespec(nanoseconds, &abstime);
return pthread_cond_timedwait(cond, mutex, &abstime);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment