21

The pthread_mutex_timedlock documentation says that abs_timeout takes a CLOCK_REALTIME. However, we all know that it is inappropriate for timing a specific duration (due to system time adjustments).

Is there a way to make pthread lock timeout on CLOCK_MONOTONIC that is portable? The same goes with pthread_cond_timedwait.

caf
  • 225,337
  • 36
  • 308
  • 455
Zach Saw
  • 4,188
  • 3
  • 31
  • 46

3 Answers3

22

Having looked at the documentation and pthread.h, I can't find a way to make pthread_mutex_timedlock use CLOCK_MONOTONIC so I assume that's not (currently) possible. For pthread_cond_timedwait, however, you can use code like this:

pthread_condattr_t attr;
pthread_cond_t cond;
/* ... */
pthread_condattr_init(&attr);
pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
pthread_cond_init(&cond, &attr);

I've omitted error code checking for clarity, but of course you should do that.

I assume that CLOCK_REALTIME is used because it's always available whereas in principle CLOCK_MONOTONIC is optional. Also, I wonder if setting absolute timeouts makes it easier to recover after system calls get interrupted by signals and the like.

However, it does seem quite inconsistent that the clock can be set in some cases and not others - there really should be a pthread_mutexattr_setclock(), but alas there does not seem to be one. I guess you'll just have to hope someone doesn't set the clock!

Cartroo
  • 4,061
  • 18
  • 22
  • 4
    This is good on Linux. `pthread_condattr_setclock` is not available on OS X and I have not been able to find a solution that works on OS X. – andrewrk Jul 02 '15 at 01:57
  • Seems like other people have run into this too: https://github.com/nanomsg/nanomsg/issues/10 – Cartroo Jul 02 '15 at 05:24
  • I'm about to do some experimenting, but I may have stumbled onto a solution over here: http://stackoverflow.com/questions/11338899/are-there-any-well-behaved-posix-interval-timers/31174803#31174803 – andrewrk Jul 02 '15 at 05:43
2

On OS X and FreeBSD, you can use kqueue and kevent. See my answer here: https://stackoverflow.com/a/31174803/432

Community
  • 1
  • 1
andrewrk
  • 28,604
  • 25
  • 89
  • 105
1

There is no way to change clock for pthread_mutex_timedlock in GLIBC yet. Maybe it's due to backward compatibility, the MONOTONIC clock was introduced later than REALTIME, so there are a lot of software which is using such function and replacement CLOCK may affect on this.

Solution/s for Linux:

  • You can found the source code of pthread_mutex_timedlock here and it is based on syscall of FUTEX which uses MONOTONIC by default. So you can implement your own mutex by using this article and it may be a good and robust solution.