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

PROLOG

6       This  manual  page is part of the POSIX Programmer's Manual.  The Linux
7       implementation of this interface may differ (consult the  corresponding
8       Linux  manual page for details of Linux behavior), or the interface may
9       not be implemented on Linux.
10

NAME

12       pthread_cond_timedwait, pthread_cond_wait - wait on a condition
13

SYNOPSIS

15       #include <pthread.h>
16
17       int pthread_cond_timedwait(pthread_cond_t *restrict cond,
18              pthread_mutex_t *restrict mutex,
19              const struct timespec *restrict abstime);
20       int pthread_cond_wait(pthread_cond_t *restrict cond,
21              pthread_mutex_t *restrict mutex);
22
23

DESCRIPTION

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

RETURN VALUE

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

ERRORS

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

EXAMPLES

128       None.
129

APPLICATION USAGE

131       None.
132

RATIONALE

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

FUTURE DIRECTIONS

289       None.
290

SEE ALSO

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