1PTHREAD_COND_TIMEDWAIT(P)  POSIX Programmer's Manual PTHREAD_COND_TIMEDWAIT(P)
2
3
4

NAME

6       pthread_cond_timedwait, pthread_cond_wait - wait on a condition
7

SYNOPSIS

9       #include <pthread.h>
10
11       int pthread_cond_timedwait(pthread_cond_t *restrict cond,
12              pthread_mutex_t *restrict mutex,
13              const struct timespec *restrict abstime);
14       int pthread_cond_wait(pthread_cond_t *restrict cond,
15              pthread_mutex_t *restrict mutex);
16
17

DESCRIPTION

19       The  pthread_cond_timedwait()  and  pthread_cond_wait() functions shall
20       block on a condition variable. They shall be called with  mutex  locked
21       by the calling thread or undefined behavior results.
22
23       These  functions  atomically release mutex and cause the calling thread
24       to block on the condition variable cond; atomically here means  "atomi‐
25       cally  with  respect  to access by another thread to the mutex and then
26       the condition variable". That is, if another thread is able to  acquire
27       the  mutex after the about-to-block thread has released it, then a sub‐
28       sequent call to pthread_cond_broadcast()  or  pthread_cond_signal()  in
29       that  thread shall behave as if it were issued after the about-to-block
30       thread has blocked.
31
32       Upon successful return, the mutex shall have been locked and  shall  be
33       owned by the calling thread.
34
35       When  using  condition  variables  there  is always a Boolean predicate
36       involving shared variables associated with each condition wait that  is
37       true   if   the  thread  should  proceed.  Spurious  wakeups  from  the
38       pthread_cond_timedwait() or pthread_cond_wait()  functions  may  occur.
39       Since  the  return from pthread_cond_timedwait() or pthread_cond_wait()
40       does not imply anything about the value of this predicate,  the  predi‐
41       cate should be re-evaluated upon such return.
42
43       The   effect   of   using   more   than   one   mutex   for  concurrent
44       pthread_cond_timedwait() or pthread_cond_wait() operations on the  same
45       condition  variable is undefined; that is, a condition variable becomes
46       bound to a unique mutex when a thread waits on the condition  variable,
47       and this (dynamic) binding shall end when the wait returns.
48
49       A  condition  wait (whether timed or not) is a cancellation point. When
50       the cancelability enable state of  a  thread  is  set  to  PTHREAD_CAN‐
51       CEL_DEFERRED, a side effect of acting upon a cancellation request while
52       in a condition wait is that the mutex is (in effect) re-acquired before
53       calling the first cancellation cleanup handler. The effect is as if the
54       thread were unblocked, allowed to execute up to the point of  returning
55       from  the  call to pthread_cond_timedwait() or pthread_cond_wait(), but
56       at that point notices the cancellation request and instead of returning
57       to  the  caller  of  pthread_cond_timedwait()  or  pthread_cond_wait(),
58       starts the thread cancellation activities, which includes calling  can‐
59       cellation cleanup handlers.
60
61       A  thread  that  has  been unblocked because it has been canceled while
62       blocked in a call to  pthread_cond_timedwait()  or  pthread_cond_wait()
63       shall  not  consume  any  condition signal that may be directed concur‐
64       rently at the condition variable if there are other threads blocked  on
65       the condition variable.
66
67       The   pthread_cond_timedwait()   function   shall   be   equivalent  to
68       pthread_cond_wait(), except that an error is returned if  the  absolute
69       time  specified  by  abstime  passes  (that  is,  system time equals or
70       exceeds abstime) before the condition cond is signaled or  broadcasted,
71       or if the absolute time specified by abstime has already been passed at
72       the time of the call.
73
74       If the Clock Selection option  is  supported,  the  condition  variable
75       shall  have  a  clock attribute which specifies the clock that shall be
76       used to measure the time specified by the abstime argument.  When  such
77       timeouts  occur, pthread_cond_timedwait() shall nonetheless release and
78       re-acquire the mutex referenced by mutex. The  pthread_cond_timedwait()
79       function is also a cancellation point.
80
81       If  a signal is delivered to a thread waiting for a condition variable,
82       upon return from the signal handler the thread resumes waiting for  the
83       condition  variable  as  if  it was not interrupted, or it shall return
84       zero due to spurious wakeup.
85

RETURN VALUE

87       Except in the case of [ETIMEDOUT], all these error checks shall act  as
88       if  they  were performed immediately at the beginning of processing for
89       the function and shall cause an error return, in effect, prior to modi‐
90       fying  the state of the mutex specified by mutex or the condition vari‐
91       able specified by cond.
92
93       Upon successful completion, a value of zero shall be  returned;  other‐
94       wise, an error number shall be returned to indicate the error.
95

ERRORS

97       The pthread_cond_timedwait() function shall fail if:
98
99       ETIMEDOUT
100              The  time  specified  by abstime to pthread_cond_timedwait() has
101              passed.
102
103
104       The pthread_cond_timedwait() and pthread_cond_wait() functions may fail
105       if:
106
107       EINVAL The value specified by cond, mutex, or abstime is invalid.
108
109       EINVAL Different     mutexes     were     supplied    for    concurrent
110              pthread_cond_timedwait() or  pthread_cond_wait()  operations  on
111              the same condition variable.
112
113       EPERM  The mutex was not owned by the current thread at the time of the
114              call.
115
116
117       These functions shall not return an error code of [EINTR].
118
119       The following sections are informative.
120

EXAMPLES

122       None.
123

APPLICATION USAGE

125       None.
126

RATIONALE

128   Condition Wait Semantics
129       It  is  important   to   note   that   when   pthread_cond_wait()   and
130       pthread_cond_timedwait() return without error, the associated predicate
131       may still be false. Similarly,  when  pthread_cond_timedwait()  returns
132       with  the timeout error, the associated predicate may be true due to an
133       unavoidable race between the expiration of the timeout and  the  predi‐
134       cate state change.
135
136       Some  implementations, particularly on a multi-processor, may sometimes
137       cause multiple threads to wake up when the condition variable  is  sig‐
138       naled simultaneously on different processors.
139
140       In  general,  whenever  a condition wait returns, the thread has to re-
141       evaluate the predicate associated with the condition wait to  determine
142       whether  it  can safely proceed, should wait again, or should declare a
143       timeout. A return from the wait does  not  imply  that  the  associated
144       predicate is either true or false.
145
146       It is thus recommended that a condition wait be enclosed in the equiva‐
147       lent of a "while loop" that checks the predicate.
148
149   Timed Wait Semantics
150       An absolute time measure was chosen for specifying the timeout  parame‐
151       ter  for  two  reasons.  First,  a  relative time measure can be easily
152       implemented on top of a function  that  specifies  absolute  time,  but
153       there  is a race condition associated with specifying an absolute time‐
154       out on top of a function that specifies relative timeouts.   For  exam‐
155       ple, assume that clock_gettime() returns the current time and cond_rel‐
156       ative_timed_wait() uses relative timeouts:
157
158
159              clock_gettime(CLOCK_REALTIME, &now)
160              reltime = sleep_til_this_absolute_time -now;
161              cond_relative_timed_wait(c, m, &reltime);
162
163       If the thread is preempted between the first  statement  and  the  last
164       statement, the thread blocks for too long. Blocking, however, is irrel‐
165       evant if an absolute timeout is used. An absolute timeout also need not
166       be  recomputed  if  it  is  used multiple times in a loop, such as that
167       enclosing a condition wait.
168
169       For cases when the system clock is advanced discontinuously by an oper‐
170       ator, it is expected that implementations process any timed wait expir‐
171       ing at an intervening time as if that time had actually occurred.
172
173   Cancellation and Condition Wait
174       A condition wait, whether timed or not, is a cancellation  point.  That
175       is,  the  functions pthread_cond_wait() or pthread_cond_timedwait() are
176       points where a pending (or concurrent) cancellation request is noticed.
177       The  reason  for  this  is that an indefinite wait is possible at these
178       points-whatever event is being waited  for,  even  if  the  program  is
179       totally  correct, might never occur; for example, some input data being
180       awaited might never be sent. By making condition  wait  a  cancellation
181       point,  the thread can be canceled and perform its cancellation cleanup
182       handler even though it may be stuck in some indefinite wait.
183
184       A side effect of acting on a cancellation request  while  a  thread  is
185       blocked on a condition variable is to re-acquire the mutex before call‐
186       ing any of the cancellation cleanup handlers. This is done in order  to
187       ensure  that  the  cancellation cleanup handler is executed in the same
188       state as the critical code that lies both before and after the call  to
189       the  condition wait function. This rule is also required when interfac‐
190       ing to POSIX threads from languages, such as  Ada  or  C++,  which  may
191       choose to map cancellation onto a language exception; this rule ensures
192       that each exception handler guarding  a  critical  section  can  always
193       safely  depend upon the fact that the associated mutex has already been
194       locked regardless of exactly where  within  the  critical  section  the
195       exception  was  raised. Without this rule, there would not be a uniform
196       rule that exception handlers could follow regarding the  lock,  and  so
197       coding would become very cumbersome.
198
199       Therefore,  since  some statement has to be made regarding the state of
200       the lock when a cancellation is delivered during a wait,  a  definition
201       has been chosen that makes application coding most convenient and error
202       free.
203
204       When acting on a cancellation request while a thread is  blocked  on  a
205       condition  variable,  the implementation is required to ensure that the
206       thread does not consume any condition signals directed at  that  condi‐
207       tion  variable if there are any other threads waiting on that condition
208       variable. This rule is specified in order to avoid deadlock  conditions
209       that  could  occur  if  these two independent requests (one acting on a
210       thread and the other acting on the condition variable)  were  not  pro‐
211       cessed independently.
212
213   Performance of Mutexes and Condition Variables
214       Mutexes  are  expected  to  be locked only for a few instructions. This
215       practice is almost automatically enforced by the desire of  programmers
216       to  avoid  long  serial  regions of execution (which would reduce total
217       effective parallelism).
218
219       When using mutexes and condition variables, one tries  to  ensure  that
220       the usual case is to lock the mutex, access shared data, and unlock the
221       mutex. Waiting on a condition variable should be a relatively rare sit‐
222       uation.  For  example,  when  implementing a read-write lock, code that
223       acquires a read-lock typically needs only to  increment  the  count  of
224       readers  (under  mutual-exclusion) and return. The calling thread would
225       actually wait on the condition variable only when there is  already  an
226       active  writer.  So  the  efficiency  of a synchronization operation is
227       bounded by the cost of mutex lock/unlock and  not  by  condition  wait.
228       Note that in the usual case there is no context switch.
229
230       This is not to say that the efficiency of condition waiting is unimpor‐
231       tant.  Since there needs to be at least one context switch per Ada ren‐
232       dezvous,  the  efficiency  of waiting on a condition variable is impor‐
233       tant. The cost of waiting on a condition variable should be little more
234       than  the minimal cost for a context switch plus the time to unlock and
235       lock the mutex.
236
237   Features of Mutexes and Condition Variables
238       It had been suggested that the mutex acquisition and release be  decou‐
239       pled  from condition wait. This was rejected because it is the combined
240       nature of the operation that, in fact, facilitates realtime implementa‐
241       tions. Those implementations can atomically move a high-priority thread
242       between the condition variable and the mutex in a manner that is trans‐
243       parent  to the caller. This can prevent extra context switches and pro‐
244       vide more deterministic acquisition of a mutex when the waiting  thread
245       is  signaled.  Thus,  fairness  and  priority  issues can be dealt with
246       directly by the scheduling discipline.  Furthermore, the current condi‐
247       tion wait operation matches existing practice.
248
249   Scheduling Behavior of Mutexes and Condition Variables
250       Synchronization  primitives  that  attempt to interfere with scheduling
251       policy by specifying  an  ordering  rule  are  considered  undesirable.
252       Threads waiting on mutexes and condition variables are selected to pro‐
253       ceed in an order dependent upon the scheduling policy  rather  than  in
254       some fixed order (for example, FIFO or priority).  Thus, the scheduling
255       policy determines which thread(s) are awakened and allowed to proceed.
256
257   Timed Condition Wait
258       The pthread_cond_timedwait() function allows an application to give  up
259       waiting  for  a  particular  condition after a given amount of time. An
260       example of its use follows:
261
262
263              (void) pthread_mutex_lock(&t.mn);
264                      t.waiters++;
265                  clock_gettime(CLOCK_REALTIME, &ts);
266                  ts.tv_sec += 5;
267                  rc = 0;
268                  while (! mypredicate(&t) && rc == 0)
269                      rc = pthread_cond_timedwait(&t.cond, &t.mn, &ts);
270                  t.waiters--;
271                  if (rc == 0) setmystate(&t);
272              (void) pthread_mutex_unlock(&t.mn);
273
274       By making the timeout parameter absolute, it does not need to be recom‐
275       puted  each  time  the  program  checks its blocking predicate.  If the
276       timeout was relative, it would have to be recomputed before each  call.
277       This  would  be especially difficult since such code would need to take
278       into account the possibility of extra wakeups that  result  from  extra
279       broadcasts  or  signals  on  the  condition  variable that occur before
280       either the predicate is true or the timeout is due.
281

FUTURE DIRECTIONS

283       None.
284

SEE ALSO

286       pthread_cond_signal() , pthread_cond_broadcast() , the Base Definitions
287       volume of IEEE Std 1003.1-2001, <pthread.h>
288
290       Portions  of  this text are reprinted and reproduced in electronic form
291       from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology
292       --  Portable  Operating  System  Interface (POSIX), The Open Group Base
293       Specifications Issue 6, Copyright (C) 2001-2003  by  the  Institute  of
294       Electrical  and  Electronics  Engineers, Inc and The Open Group. In the
295       event of any discrepancy between this version and the original IEEE and
296       The  Open Group Standard, the original IEEE and The Open Group Standard
297       is the referee document. The original Standard can be  obtained  online
298       at http://www.opengroup.org/unix/online.html .
299
300
301
302IEEE/The Open Group                  2003            PTHREAD_COND_TIMEDWAIT(P)
Impressum