What time function do I need to use with pthread_cond_timedwait?
The pthread_cond_timedwait function needs an absolute time in a time timespec structure.
What time function I'm suppose to use to obtain the absolute time. I saw a lot of example on the web and I found almost all time function used. (ftime, clock, gettimeofday, clock_gettime (with all possible CLOCK_...).
The pthread_cond_timedwait uses an absolute time. Will this waiting time affected by changing the time of the machine? Also if I get the absolute time with one of the time function, if the time of the machine开发者_StackOverflow社区 change between the get and the addition of the delta time this will affect the wait time? Is there a possibility to wait for an event with a relative time instead?
The function to use is clock_gettime()
with the clock id of the condition variable. This clock id is CLOCK_REALTIME
by default but can be changed (such as to CLOCK_MONOTONIC
) by initializing the condition variable with a pthread_condattr_t
on which pthread_condattr_setclock()
has been called.
Using time()
is not a good idea because this is not guaranteed to equal tv_sec
of a clock_gettime(CLOCK_REALTIME)
. In some cases this can cause your program to busy-wait for time()
to reach the second that was already reached by clock_gettime(CLOCK_REALTIME)
a short while ago.
I've used clock_gettime
with CLOCK_REALTIME
myself. That should work satisfactorily and allow you to easily create an absolute timespec to timeout at.
Indeed there's a possibility that the machine time will advance while you do the wait setup. In general if you're waiting for a small enough amount of time that this would matter, you won't be getting as close to your requested wakeup time as you hope anyway. If your requested time has already passed by the time the timedwait call is made, it should just wake up immediately.
Solaris provides pthread_cond_reltimedwait_np
, (np to mean non-portable) but I'm not aware of any such function on Linux. I'd suggest just waiting on the absolute time and, if needed, implementing a relative wait yourself.
timespec
is just a time in seconds (time_t
) with additional nanoseconds. You can use relative time with cond_relative_timed_wait
.
To obtain current system time in time_t
form call time(NULL);
from "time.h". More accurate would be to use
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
which will return also nanoseconds.
Other functions can be used as well but the final result must be converted to number of seconds and number of nanoseconds.
精彩评论