How to use sem_timedwait with CLOCK_MONOTONIC?

Adhemerval Zanella adhemerval.zanella@linaro.org
Thu Feb 16 12:09:00 GMT 2017



On 16/02/2017 09:06, Alexandre Bique wrote:
> Hi,
> 
> I'm working on real-time audio project, and very often the libc
> syscalls only supports CLOCK_REALTIME, where I would need
> CLOCK_MONOTONIC to avoid issues with NTP time changes.
> 
> Do you know any workaround sem_timedwait()?
> 
> Many thanks,
> 

POSIX sem_timedwait is not really implemented as a direct wrapper to a syscall,
but it rather uses a combination of atomic operation and futex syscall. The main
problem is 'sem_timedwait' is POSIX explicit states timeout argument should
be explicit handled as CLOCK_REALTIME [1].

It is already being tracked by BZ#14717 [2] and a possible solution is not that
hard since futex syscall with FUTEX_WAIT_BITSET (which is used on sem_timedwait)
without FUTEX_CLOCK_REALTIME (default value) is handled as CLOCK_MONOTONIC by
kernel.  The main issue is *how* to expose this interface to user.

It was noted on [3] that we can either support QNX 'sem_timedwait_monotonic'
or add an interface like 'sem_timedwait_np'.

Now for a workaround I would advise use another API that does support clock
such pthread_cond_timedwait [4].  GLIBC implementation will internally
convert the absolute timeout to a relative one.

You can also try to mimic internal glibc implementation on sem_timedwait
and change futex call to omit the FUTEX_CLOCK_REALTIME.

[1] http://pubs.opengroup.org/onlinepubs/9699919799/
[2] https://sourceware.org/bugzilla/show_bug.cgi?id=14717
[3] https://bugzilla.kernel.org/show_bug.cgi?id=112521
[4] http://stackoverflow.com/questions/29153310/how-would-i-cope-with-changes-to-the-system-time-while-doing-sem-timedwait



More information about the Libc-help mailing list