CLOCK_MONOTONIC and pthread_mutex_timedlock / pthread_cond_timedwait

十年热恋 提交于 2019-12-03 05:49:16

问题


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.


回答1:


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!




回答2:


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



来源:https://stackoverflow.com/questions/14248033/clock-monotonic-and-pthread-mutex-timedlock-pthread-cond-timedwait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!