How to use sem_timedwait with CLOCK_MONOTONIC?

Adhemerval Zanella
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.


More information about the Libc-help mailing list