Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 295
Vincent Avatar asked Jun 09 '10 13:06

Vincent


People also ask

How does pthread_ cond_ timedwait work?

The pthread_cond_wait() function blocks the calling thread, waiting for the condition specified by cond to be signaled or broadcast to. When pthread_cond_wait() is called, the calling thread must have mutex locked. The pthread_cond_wait() function atomically unlocks mutex and performs the wait for the condition.

Does Pthread_cond_wait unlock mutex?

pthread_cond_wait() simultaneously unlocks the mutex and begins waiting for the condition variable to be signalled. thus you must always have ownership of the mutex before invoking it.

Which one of the given error code will not return by the Pthread_mutex_timedlock () function?

A deadlock condition was detected or the current thread already owns the mutex. This function shall not return an error code of [EINTR].

What is Pthread_cond_broadcast?

The pthread_cond_broadcast() function shall unblock all threads currently blocked on the specified condition variable cond. The pthread_cond_signal() function shall unblock at least one of the threads that are blocked on the specified condition variable cond (if any threads are blocked on cond).


1 Answers

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.

like image 97
jilles Avatar answered Sep 19 '22 15:09

jilles