1PTHREAD_COND_TIMEDWAIT(3P) POSIX Programmer's ManualPTHREAD_COND_TIMEDWAIT(3P)
2
3
4
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
11
13 pthread_cond_timedwait, pthread_cond_wait — wait on a condition
14
16 #include <pthread.h>
17
18 int pthread_cond_timedwait(pthread_cond_t *restrict cond,
19 pthread_mutex_t *restrict mutex,
20 const struct timespec *restrict abstime);
21 int pthread_cond_wait(pthread_cond_t *restrict cond,
22 pthread_mutex_t *restrict mutex);
23
25 The pthread_cond_timedwait() and pthread_cond_wait() functions shall
26 block on a condition variable. The application shall ensure that these
27 functions are called with mutex locked by the calling thread; other‐
28 wise, an error (for PTHREAD_MUTEX_ERRORCHECK and robust mutexes) or
29 undefined behavior (for other mutexes) results.
30
31 These functions atomically release mutex and cause the calling thread
32 to block on the condition variable cond; atomically here means ``atomi‐
33 cally with respect to access by another thread to the mutex and then
34 the condition variable''. That is, if another thread is able to acquire
35 the mutex after the about-to-block thread has released it, then a sub‐
36 sequent call to pthread_cond_broadcast() or pthread_cond_signal() in
37 that thread shall behave as if it were issued after the about-to-block
38 thread has blocked.
39
40 Upon successful return, the mutex shall have been locked and shall be
41 owned by the calling thread. If mutex is a robust mutex where an owner
42 terminated while holding the lock and the state is recoverable, the
43 mutex shall be acquired even though the function returns an error code.
44
45 When using condition variables there is always a Boolean predicate
46 involving shared variables associated with each condition wait that is
47 true if the thread should proceed. Spurious wakeups from the
48 pthread_cond_timedwait() or pthread_cond_wait() functions may occur.
49 Since the return from pthread_cond_timedwait() or pthread_cond_wait()
50 does not imply anything about the value of this predicate, the predi‐
51 cate should be re-evaluated upon such return.
52
53 When a thread waits on a condition variable, having specified a partic‐
54 ular mutex to either the pthread_cond_timedwait() or the
55 pthread_cond_wait() operation, a dynamic binding is formed between that
56 mutex and condition variable that remains in effect as long as at least
57 one thread is blocked on the condition variable. During this time, the
58 effect of an attempt by any thread to wait on that condition variable
59 using a different mutex is undefined. Once all waiting threads have
60 been unblocked (as by the pthread_cond_broadcast() operation), the next
61 wait operation on that condition variable shall form a new dynamic
62 binding with the mutex specified by that wait operation. Even though
63 the dynamic binding between condition variable and mutex may be removed
64 or replaced between the time a thread is unblocked from a wait on the
65 condition variable and the time that it returns to the caller or begins
66 cancellation cleanup, the unblocked thread shall always re-acquire the
67 mutex specified in the condition wait operation call from which it is
68 returning.
69
70 A condition wait (whether timed or not) is a cancellation point. When
71 the cancelability type of a thread is set to PTHREAD_CANCEL_DEFERRED, a
72 side-effect of acting upon a cancellation request while in a condition
73 wait is that the mutex is (in effect) re-acquired before calling the
74 first cancellation cleanup handler. The effect is as if the thread were
75 unblocked, allowed to execute up to the point of returning from the
76 call to pthread_cond_timedwait() or pthread_cond_wait(), but at that
77 point notices the cancellation request and instead of returning to the
78 caller of pthread_cond_timedwait() or pthread_cond_wait(), starts the
79 thread cancellation activities, which includes calling cancellation
80 cleanup handlers.
81
82 A thread that has been unblocked because it has been canceled while
83 blocked in a call to pthread_cond_timedwait() or pthread_cond_wait()
84 shall not consume any condition signal that may be directed concur‐
85 rently at the condition variable if there are other threads blocked on
86 the condition variable.
87
88 The pthread_cond_timedwait() function shall be equivalent to
89 pthread_cond_wait(), except that an error is returned if the absolute
90 time specified by abstime passes (that is, system time equals or
91 exceeds abstime) before the condition cond is signaled or broadcasted,
92 or if the absolute time specified by abstime has already been passed at
93 the time of the call. When such timeouts occur, pthread_cond_timed‐
94 wait() shall nonetheless release and re-acquire the mutex referenced by
95 mutex, and may consume a condition signal directed concurrently at the
96 condition variable.
97
98 The condition variable shall have a clock attribute which specifies the
99 clock that shall be used to measure the time specified by the abstime
100 argument. The pthread_cond_timedwait() function is also a cancellation
101 point.
102
103 If a signal is delivered to a thread waiting for a condition variable,
104 upon return from the signal handler the thread resumes waiting for the
105 condition variable as if it was not interrupted, or it shall return
106 zero due to spurious wakeup.
107
108 The behavior is undefined if the value specified by the cond or mutex
109 argument to these functions does not refer to an initialized condition
110 variable or an initialized mutex object, respectively.
111
113 Except in the case of [ETIMEDOUT], all these error checks shall act as
114 if they were performed immediately at the beginning of processing for
115 the function and shall cause an error return, in effect, prior to modi‐
116 fying the state of the mutex specified by mutex or the condition vari‐
117 able specified by cond.
118
119 Upon successful completion, a value of zero shall be returned; other‐
120 wise, an error number shall be returned to indicate the error.
121
123 These functions shall fail if:
124
125 ENOTRECOVERABLE
126 The state protected by the mutex is not recoverable.
127
128 EOWNERDEAD
129 The mutex is a robust mutex and the process containing the pre‐
130 vious owning thread terminated while holding the mutex lock. The
131 mutex lock shall be acquired by the calling thread and it is up
132 to the new owner to make the state consistent.
133
134 EPERM The mutex type is PTHREAD_MUTEX_ERRORCHECK or the mutex is a
135 robust mutex, and the current thread does not own the mutex.
136
137 The pthread_cond_timedwait() function shall fail if:
138
139 ETIMEDOUT
140 The time specified by abstime to pthread_cond_timedwait() has
141 passed.
142
143 EINVAL The abstime argument specified a nanosecond value less than zero
144 or greater than or equal to 1000 million.
145
146 These functions may fail if:
147
148 EOWNERDEAD
149 The mutex is a robust mutex and the previous owning thread ter‐
150 minated while holding the mutex lock. The mutex lock shall be
151 acquired by the calling thread and it is up to the new owner to
152 make the state consistent.
153
154 These functions shall not return an error code of [EINTR].
155
156 The following sections are informative.
157
159 None.
160
162 Applications that have assumed that non-zero return values are errors
163 will need updating for use with robust mutexes, since a valid return
164 for a thread acquiring a mutex which is protecting a currently incon‐
165 sistent state is [EOWNERDEAD]. Applications that do not check the
166 error returns, due to ruling out the possibility of such errors aris‐
167 ing, should not use robust mutexes. If an application is supposed to
168 work with normal and robust mutexes, it should check all return values
169 for error conditions and if necessary take appropriate action.
170
172 If an implementation detects that the value specified by the cond argu‐
173 ment to pthread_cond_timedwait() or pthread_cond_wait() does not refer
174 to an initialized condition variable, or detects that the value speci‐
175 fied by the mutex argument to pthread_cond_timedwait() or
176 pthread_cond_wait() does not refer to an initialized mutex object, it
177 is recommended that the function should fail and report an [EINVAL]
178 error.
179
180 Condition Wait Semantics
181 It is important to note that when pthread_cond_wait() and
182 pthread_cond_timedwait() return without error, the associated predicate
183 may still be false. Similarly, when pthread_cond_timedwait() returns
184 with the timeout error, the associated predicate may be true due to an
185 unavoidable race between the expiration of the timeout and the predi‐
186 cate state change.
187
188 The application needs to recheck the predicate on any return because it
189 cannot be sure there is another thread waiting on the thread to handle
190 the signal, and if there is not then the signal is lost. The burden is
191 on the application to check the predicate.
192
193 Some implementations, particularly on a multi-processor, may sometimes
194 cause multiple threads to wake up when the condition variable is sig‐
195 naled simultaneously on different processors.
196
197 In general, whenever a condition wait returns, the thread has to re-
198 evaluate the predicate associated with the condition wait to determine
199 whether it can safely proceed, should wait again, or should declare a
200 timeout. A return from the wait does not imply that the associated
201 predicate is either true or false.
202
203 It is thus recommended that a condition wait be enclosed in the equiva‐
204 lent of a ``while loop'' that checks the predicate.
205
206 Timed Wait Semantics
207 An absolute time measure was chosen for specifying the timeout parame‐
208 ter for two reasons. First, a relative time measure can be easily
209 implemented on top of a function that specifies absolute time, but
210 there is a race condition associated with specifying an absolute time‐
211 out on top of a function that specifies relative timeouts. For example,
212 assume that clock_gettime() returns the current time and cond_rela‐
213 tive_timed_wait() uses relative timeouts:
214
215 clock_gettime(CLOCK_REALTIME, &now)
216 reltime = sleep_til_this_absolute_time -now;
217 cond_relative_timed_wait(c, m, &reltime);
218
219 If the thread is preempted between the first statement and the last
220 statement, the thread blocks for too long. Blocking, however, is irrel‐
221 evant if an absolute timeout is used. An absolute timeout also need not
222 be recomputed if it is used multiple times in a loop, such as that
223 enclosing a condition wait.
224
225 For cases when the system clock is advanced discontinuously by an oper‐
226 ator, it is expected that implementations process any timed wait expir‐
227 ing at an intervening time as if that time had actually occurred.
228
229 Cancellation and Condition Wait
230 A condition wait, whether timed or not, is a cancellation point. That
231 is, the functions pthread_cond_wait() or pthread_cond_timedwait() are
232 points where a pending (or concurrent) cancellation request is noticed.
233 The reason for this is that an indefinite wait is possible at these
234 points—whatever event is being waited for, even if the program is
235 totally correct, might never occur; for example, some input data being
236 awaited might never be sent. By making condition wait a cancellation
237 point, the thread can be canceled and perform its cancellation cleanup
238 handler even though it may be stuck in some indefinite wait.
239
240 A side-effect of acting on a cancellation request while a thread is
241 blocked on a condition variable is to re-acquire the mutex before call‐
242 ing any of the cancellation cleanup handlers. This is done in order to
243 ensure that the cancellation cleanup handler is executed in the same
244 state as the critical code that lies both before and after the call to
245 the condition wait function. This rule is also required when interfac‐
246 ing to POSIX threads from languages, such as Ada or C++, which may
247 choose to map cancellation onto a language exception; this rule ensures
248 that each exception handler guarding a critical section can always
249 safely depend upon the fact that the associated mutex has already been
250 locked regardless of exactly where within the critical section the
251 exception was raised. Without this rule, there would not be a uniform
252 rule that exception handlers could follow regarding the lock, and so
253 coding would become very cumbersome.
254
255 Therefore, since some statement has to be made regarding the state of
256 the lock when a cancellation is delivered during a wait, a definition
257 has been chosen that makes application coding most convenient and error
258 free.
259
260 When acting on a cancellation request while a thread is blocked on a
261 condition variable, the implementation is required to ensure that the
262 thread does not consume any condition signals directed at that condi‐
263 tion variable if there are any other threads waiting on that condition
264 variable. This rule is specified in order to avoid deadlock conditions
265 that could occur if these two independent requests (one acting on a
266 thread and the other acting on the condition variable) were not pro‐
267 cessed independently.
268
269 Performance of Mutexes and Condition Variables
270 Mutexes are expected to be locked only for a few instructions. This
271 practice is almost automatically enforced by the desire of programmers
272 to avoid long serial regions of execution (which would reduce total
273 effective parallelism).
274
275 When using mutexes and condition variables, one tries to ensure that
276 the usual case is to lock the mutex, access shared data, and unlock the
277 mutex. Waiting on a condition variable should be a relatively rare sit‐
278 uation. For example, when implementing a read-write lock, code that
279 acquires a read-lock typically needs only to increment the count of
280 readers (under mutual-exclusion) and return. The calling thread would
281 actually wait on the condition variable only when there is already an
282 active writer. So the efficiency of a synchronization operation is
283 bounded by the cost of mutex lock/unlock and not by condition wait.
284 Note that in the usual case there is no context switch.
285
286 This is not to say that the efficiency of condition waiting is unimpor‐
287 tant. Since there needs to be at least one context switch per Ada ren‐
288 dezvous, the efficiency of waiting on a condition variable is impor‐
289 tant. The cost of waiting on a condition variable should be little more
290 than the minimal cost for a context switch plus the time to unlock and
291 lock the mutex.
292
293 Features of Mutexes and Condition Variables
294 It had been suggested that the mutex acquisition and release be decou‐
295 pled from condition wait. This was rejected because it is the combined
296 nature of the operation that, in fact, facilitates realtime implementa‐
297 tions. Those implementations can atomically move a high-priority thread
298 between the condition variable and the mutex in a manner that is trans‐
299 parent to the caller. This can prevent extra context switches and pro‐
300 vide more deterministic acquisition of a mutex when the waiting thread
301 is signaled. Thus, fairness and priority issues can be dealt with
302 directly by the scheduling discipline. Furthermore, the current condi‐
303 tion wait operation matches existing practice.
304
305 Scheduling Behavior of Mutexes and Condition Variables
306 Synchronization primitives that attempt to interfere with scheduling
307 policy by specifying an ordering rule are considered undesirable.
308 Threads waiting on mutexes and condition variables are selected to pro‐
309 ceed in an order dependent upon the scheduling policy rather than in
310 some fixed order (for example, FIFO or priority). Thus, the scheduling
311 policy determines which thread(s) are awakened and allowed to proceed.
312
313 Timed Condition Wait
314 The pthread_cond_timedwait() function allows an application to give up
315 waiting for a particular condition after a given amount of time. An
316 example of its use follows:
317
318 (void) pthread_mutex_lock(&t.mn);
319 t.waiters++;
320 clock_gettime(CLOCK_REALTIME, &ts);
321 ts.tv_sec += 5;
322 rc = 0;
323 while (! mypredicate(&t) && rc == 0)
324 rc = pthread_cond_timedwait(&t.cond, &t.mn, &ts);
325 t.waiters--;
326 if (rc == 0 || mypredicate(&t))
327 setmystate(&t);
328 (void) pthread_mutex_unlock(&t.mn);
329
330 By making the timeout parameter absolute, it does not need to be recom‐
331 puted each time the program checks its blocking predicate. If the time‐
332 out was relative, it would have to be recomputed before each call.
333 This would be especially difficult since such code would need to take
334 into account the possibility of extra wakeups that result from extra
335 broadcasts or signals on the condition variable that occur before
336 either the predicate is true or the timeout is due.
337
339 None.
340
342 pthread_cond_broadcast()
343
344 The Base Definitions volume of POSIX.1‐2008, Section 4.11, Memory Syn‐
345 chronization, <pthread.h>
346
348 Portions of this text are reprinted and reproduced in electronic form
349 from IEEE Std 1003.1, 2013 Edition, Standard for Information Technology
350 -- Portable Operating System Interface (POSIX), The Open Group Base
351 Specifications Issue 7, Copyright (C) 2013 by the Institute of Electri‐
352 cal and Electronics Engineers, Inc and The Open Group. (This is
353 POSIX.1-2008 with the 2013 Technical Corrigendum 1 applied.) In the
354 event of any discrepancy between this version and the original IEEE and
355 The Open Group Standard, the original IEEE and The Open Group Standard
356 is the referee document. The original Standard can be obtained online
357 at http://www.unix.org/online.html .
358
359 Any typographical or formatting errors that appear in this page are
360 most likely to have been introduced during the conversion of the source
361 files to man page format. To report such errors, see https://www.ker‐
362 nel.org/doc/man-pages/reporting_bugs.html .
363
364
365
366IEEE/The Open Group 2013 PTHREAD_COND_TIMEDWAIT(3P)