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
12 pthread_cond_timedwait, pthread_cond_wait — wait on a condition
13
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
24 The pthread_cond_timedwait() and pthread_cond_wait() functions shall
25 block on a condition variable. The application shall ensure that these
26 functions are called with mutex locked by the calling thread; other‐
27 wise, an error (for PTHREAD_MUTEX_ERRORCHECK and robust mutexes) or
28 undefined behavior (for other mutexes) results.
29
30 These functions atomically release mutex and cause the calling thread
31 to block on the condition variable cond; atomically here means ``atomi‐
32 cally with respect to access by another thread to the mutex and then
33 the condition variable''. That is, if another thread is able to acquire
34 the mutex after the about-to-block thread has released it, then a sub‐
35 sequent call to pthread_cond_broadcast() or pthread_cond_signal() in
36 that thread shall behave as if it were issued after the about-to-block
37 thread has blocked.
38
39 Upon successful return, the mutex shall have been locked and shall be
40 owned by the calling thread. If mutex is a robust mutex where an owner
41 terminated while holding the lock and the state is recoverable, the
42 mutex shall be acquired even though the function returns an error code.
43
44 When using condition variables there is always a Boolean predicate
45 involving shared variables associated with each condition wait that is
46 true if the thread should proceed. Spurious wakeups from the
47 pthread_cond_timedwait() or pthread_cond_wait() functions may occur.
48 Since the return from pthread_cond_timedwait() or pthread_cond_wait()
49 does not imply anything about the value of this predicate, the predi‐
50 cate should be re-evaluated upon such return.
51
52 When a thread waits on a condition variable, having specified a partic‐
53 ular mutex to either the pthread_cond_timedwait() or the
54 pthread_cond_wait() operation, a dynamic binding is formed between that
55 mutex and condition variable that remains in effect as long as at least
56 one thread is blocked on the condition variable. During this time, the
57 effect of an attempt by any thread to wait on that condition variable
58 using a different mutex is undefined. Once all waiting threads have
59 been unblocked (as by the pthread_cond_broadcast() operation), the next
60 wait operation on that condition variable shall form a new dynamic
61 binding with the mutex specified by that wait operation. Even though
62 the dynamic binding between condition variable and mutex may be removed
63 or replaced between the time a thread is unblocked from a wait on the
64 condition variable and the time that it returns to the caller or begins
65 cancellation cleanup, the unblocked thread shall always re-acquire the
66 mutex specified in the condition wait operation call from which it is
67 returning.
68
69 A condition wait (whether timed or not) is a cancellation point. When
70 the cancelability type of a thread is set to PTHREAD_CANCEL_DEFERRED, a
71 side-effect of acting upon a cancellation request while in a condition
72 wait is that the mutex is (in effect) re-acquired before calling the
73 first cancellation cleanup handler. The effect is as if the thread were
74 unblocked, allowed to execute up to the point of returning from the
75 call to pthread_cond_timedwait() or pthread_cond_wait(), but at that
76 point notices the cancellation request and instead of returning to the
77 caller of pthread_cond_timedwait() or pthread_cond_wait(), starts the
78 thread cancellation activities, which includes calling cancellation
79 cleanup handlers.
80
81 A thread that has been unblocked because it has been canceled while
82 blocked in a call to pthread_cond_timedwait() or pthread_cond_wait()
83 shall not consume any condition signal that may be directed concur‐
84 rently at the condition variable if there are other threads blocked on
85 the condition variable.
86
87 The pthread_cond_timedwait() function shall be equivalent to
88 pthread_cond_wait(), except that an error is returned if the absolute
89 time specified by abstime passes (that is, system time equals or
90 exceeds abstime) before the condition cond is signaled or broadcasted,
91 or if the absolute time specified by abstime has already been passed at
92 the time of the call. When such timeouts occur, pthread_cond_timed‐
93 wait() shall nonetheless release and re-acquire the mutex referenced by
94 mutex, and may consume a condition signal directed concurrently at the
95 condition variable.
96
97 The condition variable shall have a clock attribute which specifies the
98 clock that shall be used to measure the time specified by the abstime
99 argument. The pthread_cond_timedwait() function is also a cancellation
100 point.
101
102 If a signal is delivered to a thread waiting for a condition variable,
103 upon return from the signal handler the thread resumes waiting for the
104 condition variable as if it was not interrupted, or it shall return
105 zero due to spurious wakeup.
106
107 The behavior is undefined if the value specified by the cond or mutex
108 argument to these functions does not refer to an initialized condition
109 variable or an initialized mutex object, respectively.
110
112 Except for [ETIMEDOUT], [ENOTRECOVERABLE], and [EOWNERDEAD], all these
113 error checks shall act as if they were performed immediately at the
114 beginning of processing for the function and shall cause an error
115 return, in effect, prior to modifying the state of the mutex specified
116 by mutex or the condition variable specified by cond.
117
118 Upon successful completion, a value of zero shall be returned; other‐
119 wise, an error number shall be returned to indicate the error.
120
122 These functions shall fail if:
123
124 ENOTRECOVERABLE
125 The state protected by the mutex is not recoverable.
126
127 EOWNERDEAD
128 The mutex is a robust mutex and the process containing the pre‐
129 vious owning thread terminated while holding the mutex lock. The
130 mutex lock shall be acquired by the calling thread and it is up
131 to the new owner to make the state consistent.
132
133 EPERM The mutex type is PTHREAD_MUTEX_ERRORCHECK or the mutex is a
134 robust mutex, and the current thread does not own the mutex.
135
136 The pthread_cond_timedwait() function shall fail if:
137
138 ETIMEDOUT
139 The time specified by abstime to pthread_cond_timedwait() has
140 passed.
141
142 EINVAL The abstime argument specified a nanosecond value less than zero
143 or greater than or equal to 1000 million.
144
145 These functions may fail if:
146
147 EOWNERDEAD
148 The mutex is a robust mutex and the previous owning thread ter‐
149 minated while holding the mutex lock. The mutex lock shall be
150 acquired by the calling thread and it is up to the new owner to
151 make the state consistent.
152
153 These functions shall not return an error code of [EINTR].
154
155 The following sections are informative.
156
158 None.
159
161 Applications that have assumed that non-zero return values are errors
162 will need updating for use with robust mutexes, since a valid return
163 for a thread acquiring a mutex which is protecting a currently incon‐
164 sistent state is [EOWNERDEAD]. Applications that do not check the
165 error returns, due to ruling out the possibility of such errors aris‐
166 ing, should not use robust mutexes. If an application is supposed to
167 work with normal and robust mutexes, it should check all return values
168 for error conditions and if necessary take appropriate action.
169
171 If an implementation detects that the value specified by the cond argu‐
172 ment to pthread_cond_timedwait() or pthread_cond_wait() does not refer
173 to an initialized condition variable, or detects that the value speci‐
174 fied by the mutex argument to pthread_cond_timedwait() or
175 pthread_cond_wait() does not refer to an initialized mutex object, it
176 is recommended that the function should fail and report an [EINVAL]
177 error.
178
179 Condition Wait Semantics
180 It is important to note that when pthread_cond_wait() and
181 pthread_cond_timedwait() return without error, the associated predicate
182 may still be false. Similarly, when pthread_cond_timedwait() returns
183 with the timeout error, the associated predicate may be true due to an
184 unavoidable race between the expiration of the timeout and the predi‐
185 cate state change.
186
187 The application needs to recheck the predicate on any return because it
188 cannot be sure there is another thread waiting on the thread to handle
189 the signal, and if there is not then the signal is lost. The burden is
190 on the application to check the predicate.
191
192 Some implementations, particularly on a multi-processor, may sometimes
193 cause multiple threads to wake up when the condition variable is sig‐
194 naled simultaneously on different processors.
195
196 In general, whenever a condition wait returns, the thread has to re-
197 evaluate the predicate associated with the condition wait to determine
198 whether it can safely proceed, should wait again, or should declare a
199 timeout. A return from the wait does not imply that the associated
200 predicate is either true or false.
201
202 It is thus recommended that a condition wait be enclosed in the equiva‐
203 lent of a ``while loop'' that checks the predicate.
204
205 Timed Wait Semantics
206 An absolute time measure was chosen for specifying the timeout parame‐
207 ter for two reasons. First, a relative time measure can be easily
208 implemented on top of a function that specifies absolute time, but
209 there is a race condition associated with specifying an absolute time‐
210 out on top of a function that specifies relative timeouts. For example,
211 assume that clock_gettime() returns the current time and cond_rela‐
212 tive_timed_wait() uses relative timeouts:
213
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
319 (void) pthread_mutex_lock(&t.mn);
320 t.waiters++;
321 clock_gettime(CLOCK_REALTIME, &ts);
322 ts.tv_sec += 5;
323 rc = 0;
324 while (! mypredicate(&t) && rc == 0)
325 rc = pthread_cond_timedwait(&t.cond, &t.mn, &ts);
326 t.waiters--;
327 if (rc == 0 || mypredicate(&t))
328 setmystate(&t);
329 (void) pthread_mutex_unlock(&t.mn);
330
331 By making the timeout parameter absolute, it does not need to be recom‐
332 puted each time the program checks its blocking predicate. If the time‐
333 out was relative, it would have to be recomputed before each call.
334 This would be especially difficult since such code would need to take
335 into account the possibility of extra wakeups that result from extra
336 broadcasts or signals on the condition variable that occur before
337 either the predicate is true or the timeout is due.
338
340 None.
341
343 pthread_cond_broadcast()
344
345 The Base Definitions volume of POSIX.1‐2017, Section 4.12, Memory Syn‐
346 chronization, <pthread.h>
347
349 Portions of this text are reprinted and reproduced in electronic form
350 from IEEE Std 1003.1-2017, Standard for Information Technology -- Por‐
351 table Operating System Interface (POSIX), The Open Group Base Specifi‐
352 cations Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of
353 Electrical and Electronics Engineers, Inc and The Open Group. 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.opengroup.org/unix/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 2017 PTHREAD_COND_TIMEDWAIT(3P)