PTHREAD_COND_TIMEDWAIT(3P)
๐ PTHREAD_COND_TIMEDWAIT(3P) ๐
okay bestie, so this is a page from the POSIX Programmer's Manual โ that's the manual name, she's fancy โ and we're talking about pthread_cond_timedwait here. buckle up ๐
๐ธ PROLOG ๐ธ
This manual page is part of the POSIX Programmer's Manual. Heads up though: the Linux implementation of this interface may differ (so go check the corresponding Linux manual page for the deets on Linux behavior), or the interface may not even be implemented on Linux. iykyk ๐
โจ NAME โจ
pthread_cond_timedwait, pthread_cond_wait โ wait on a condition
๐ฆ SYNOPSIS ๐ฆ
#include <pthread.h>
int pthread_cond_timedwait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex,
const struct timespec *restrict abstime);
int pthread_cond_wait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex);
๐ซ DESCRIPTION ๐ซ
So pthread_cond_timedwait() and pthread_cond_wait() shall block on a condition variable. But like, the application has to make sure these functions get called with mutex locked by the calling thread โ otherwise you get an error (for PTHREAD_MUTEX_ERRORCHECK and robust mutexes) or straight-up undefined behavior (for every other mutex). not a vibe, don't do it ๐
These functions atomically release mutex and cause the calling thread to block on the condition variable cond. And "atomically" here means "atomically with respect to access by another thread to the mutex and then the condition variable". Translation bestie: if another thread can grab the mutex after the about-to-block thread has released it, then a subsequent call to pthread_cond_broadcast() or pthread_cond_signal() in that thread shall behave as if it were issued after the about-to-block thread has blocked. ๐ง
Upon successful return, the mutex shall have been locked and shall be owned by the calling thread. And if mutex is a robust mutex where an owner terminated while holding the lock and the state is recoverable, the mutex shall be acquired even though the function returns an error code. slay, she's persistent โจ
Now, condition variables have โจloreโจ: whenever you're using them, there's always a Boolean predicate involving shared variables that's tied to each condition wait, and it's true if the thread should proceed. Also โ and this is the part everyone forgets โ spurious wakeups from pthread_cond_timedwait() or pthread_cond_wait() may occur. Since returning from these functions does not imply anything about the value of that predicate, you should re-evaluate the predicate every time you return. periodt. ๐
When a thread waits on a condition variable and specifies a particular mutex to either pthread_cond_timedwait() or pthread_cond_wait(), a dynamic binding is formed between that mutex and condition variable, and it stays in effect as long as at least one thread is blocked on the condition variable. During that time, the effect of any thread trying to wait on that condition variable with a different mutex is undefined. Once all waiting threads have been unblocked (like via the pthread_cond_broadcast() operation), the next wait operation on that condition variable shall form a new dynamic binding with the mutex specified by that wait operation. And even though that dynamic binding may be removed or replaced between the time a thread is unblocked from a wait and the time it returns to the caller or begins cancellation cleanup, the unblocked thread shall always re-acquire the mutex specified in the condition wait operation call it's returning from. no cap ๐ซถ
A condition wait (timed or not) is a cancellation point. When the cancelability type of a thread is set to PTHREAD_CANCEL_DEFERRED, a side-effect of acting on a cancellation request while in a condition wait is that the mutex is (in effect) re-acquired before calling the first cancellation cleanup handler. The effect is as if the thread were unblocked, allowed to execute up to the point of returning from the call to pthread_cond_timedwait() or pthread_cond_wait(), but at that exact point it notices the cancellation request and โ instead of returning to the caller of pthread_cond_timedwait() or pthread_cond_wait() โ starts the thread cancellation activities, which includes calling cancellation cleanup handlers. it's giving plot twist ๐ญ
A thread that's been unblocked because it was canceled while blocked in a call to pthread_cond_timedwait() or pthread_cond_wait() shall not consume any condition signal that may be directed concurrently at the condition variable if there are other threads blocked on that condition variable. she's polite, she doesn't steal signals ๐
pthread_cond_timedwait() shall be equivalent to pthread_cond_wait(), except that an error is returned if the absolute time specified by abstime passes (that is, system time equals or exceeds abstime) before the condition cond is signaled or broadcasted, or if the absolute time specified by abstime has already passed at the time of the call. When those timeouts happen, pthread_cond_timedwait() shall nonetheless release and re-acquire the mutex referenced by mutex, and may consume a condition signal directed concurrently at the condition variable.
The condition variable shall have a clock attribute which specifies the clock that shall be used to measure the time specified by the abstime argument. And fun fact: pthread_cond_timedwait() is also a cancellation point. ๐
If a signal is delivered to a thread waiting for a condition variable, then upon return from the signal handler the thread resumes waiting for the condition variable as if it wasn't interrupted, or it shall return zero due to spurious wakeup.
โ ๏ธ and the big one: the behavior is undefined if the value specified by thecondormutexargument to these functions doesn't refer to an initialized condition variable or an initialized mutex object, respectively. like. don't. ๐
๐ฅ RETURN VALUE ๐ฅ
Except for [ETIMEDOUT], [ENOTRECOVERABLE], and [EOWNERDEAD], all these error checks shall act as if they were performed immediately at the beginning of processing for the function and shall cause an error return โ in effect, prior to modifying the state of the mutex specified by mutex or the condition variable specified by cond. efficient queen โจ
Upon successful completion, a value of zero shall be returned; otherwise, an error number shall be returned to indicate the error.
๐ ERRORS ๐
These functions shall fail if:
ENOTRECOVERABLEโ the state protected by the mutex is not recoverable. ๐ญEOWNERDEADโ the mutex is a robust mutex and the process containing the previous owning thread terminated while holding the mutex lock. The mutex lock shall be acquired by the calling thread and it's up to the new owner to make the state consistent. you inherited a mess bestie, fix itEPERMโ the mutex type isPTHREAD_MUTEX_ERRORCHECKor the mutex is a robust mutex, and the current thread does not own the mutex.
The pthread_cond_timedwait() function shall fail if:
ETIMEDOUTโ the time specified byabstimetopthread_cond_timedwait()has passed. โฐEINVALโ theabstimeargument specified a nanosecond value less than zero or greater than or equal to 1000 million.
These functions may fail if:
EOWNERDEADโ the mutex is a robust mutex and the previous owning thread terminated while holding the mutex lock. The mutex lock shall be acquired by the calling thread and it's up to the new owner to make the state consistent.
๐จ These functions shall not return an error code of [EINTR]. don't even ask.
The following sections are informative. (yes, that's a real sentence in the manual, we love a meta moment ๐ )
๐ EXAMPLES ๐
None. ๐ญ that's it. that's the section. iconic of them honestly.
๐ APPLICATION USAGE ๐
Applications that assumed non-zero return values are errors will need updating for use with robust mutexes, because a valid return for a thread acquiring a mutex that's protecting a currently inconsistent state is [EOWNERDEAD]. sneaky, right? ๐
Applications that don't check error returns โ because they ruled out the possibility of such errors arising โ should not use robust mutexes. and if an application is supposed to work with both normal and robust mutexes, it should check all return values for error conditions and take appropriate action if necessary. check your returns, bestie, it's self care ๐ซถ
๐ญ RATIONALE ๐ญ
okay so bestie, if an implementation clocks that the value you passed as cond to pthread_cond_timedwait() or pthread_cond_wait() is not actually pointing at an initialized condition variable, or that the value you passed as mutex to pthread_cond_timedwait() or pthread_cond_wait() isn't pointing at an initialized mutex object? it's recommended that the function fails and reports an [EINVAL] error. like, that's the vibe. that's the recommendation. ๐
โจ Condition Wait Semantics โจ
this part is SO important, do not skip it. when pthread_cond_wait() and pthread_cond_timedwait() return without error, the associated predicate may still be false. and yeah โ same energy the other way: when pthread_cond_timedwait() returns with the timeout error, the associated predicate may be true, because of an unavoidable race between the timeout expiring and the predicate state changing. it's giving "nobody's fault, just physics". ๐ญ
your application needs to recheck the predicate on any return, because it cannot be sure there's another thread waiting on the thread to handle the signal โ and if there isn't one, that signal is just lost. the burden of checking the predicate is on the application. periodt.
some implementations, especially on a multi-processor, may sometimes cause multiple threads to wake up when the condition variable is signaled simultaneously on different processors. iconic chaotic behavior tbh.
in general, whenever a condition wait returns, the thread has to re-evaluate the predicate associated with the condition wait to figure out whether it can safely proceed, should wait again, or should declare a timeout. a return from the wait does not imply that the associated predicate is either true or false. it implies nothing. it's just a return. ๐
so it's recommended that a condition wait be enclosed in the equivalent of a "while loop" that checks the predicate. yes bestie, the classic.
โฐ Timed Wait Semantics โฐ
so why is the timeout an absolute time measure? two reasons, and they're both good:
- a relative time measure can be easily implemented on top of a function that specifies absolute time โ but there's a race condition if you try to do absolute timeouts on top of a function that specifies relative timeouts.
- absolute timeouts are just cleaner for loops, we'll get there.
like, imagine clock_gettime() returns the current time and cond_relative_timed_wait() uses relative timeouts:
clock_gettime(CLOCK_REALTIME, &now)
reltime = sleep_til_this_absolute_time -now;
cond_relative_timed_wait(c, m, &reltime);
if the thread gets preempted between that first statement and the last statement, the thread blocks for too long. ๐ but blocking is irrelevant if an absolute timeout is used! and an absolute timeout also doesn't need to be recomputed if you use it multiple times in a loop โ like the one enclosing a condition wait. slay.
for cases when the system clock is advanced discontinuously by an operator, it's expected that implementations process any timed wait expiring at an intervening time as if that time had actually occurred. no cap.
๐ Cancellation and Condition Wait ๐
a condition wait, timed or not, is a cancellation point. that means pthread_cond_wait() or pthread_cond_timedwait() are points where a pending (or concurrent) cancellation request gets noticed.
why? because an indefinite wait is possible at these points โ whatever event is being waited for, even if the program is totally correct, might never occur. like, some input data being awaited might just... never be sent. ever. by making condition wait a cancellation point, the thread can be canceled and run its cancellation cleanup handler even though it may be stuck in some indefinite wait. ๐ซถ
now here's the side-effect, and it's a big one: when you act on a cancellation request while a thread is blocked on a condition variable, the mutex gets re-acquired before calling any of the cancellation cleanup handlers. why tho? to make sure the cancellation cleanup handler executes in the same state as the critical code that lies both before and after the call to the condition wait function.
this rule is also required when interfacing to POSIX threads from languages like Ada or C++, which may choose to map cancellation onto a language exception. this rule guarantees that each exception handler guarding a critical section can always safely depend on the fact that the associated mutex has already been locked โ regardless of exactly where within the critical section the exception was raised. without this rule there would be no uniform rule that exception handlers could follow regarding the lock, and coding would become very cumbersome. and we do not do cumbersome here.
so, since some statement has to be made about the state of the lock when a cancellation is delivered during a wait, a definition was chosen that makes application coding most convenient and error free. chef's kiss. ๐
when acting on a cancellation request while a thread is blocked on a condition variable, the implementation is required to ensure that the thread does not consume any condition signals directed at that condition variable if there are any other threads waiting on that condition variable. this rule exists to avoid deadlock conditions that could occur if those two independent requests (one acting on a thread, the other acting on the condition variable) were not processed independently. iykyk.
๐ Performance of Mutexes and Condition Variables ๐
mutexes are expected to be locked only for a few instructions. this practice is almost automatically enforced by programmers wanting to avoid long serial regions of execution (which would reduce total effective parallelism). so the vibes self-regulate. โจ
when using mutexes and condition variables, you try to make sure the usual case is: lock the mutex, access shared data, unlock the mutex. waiting on a condition variable should be a relatively rare situation.
for example, when implementing a read-write lock, code that acquires a read-lock typically only needs to increment the count of readers (under mutual-exclusion) and return. the calling thread would actually wait on the condition variable only when there is already an active writer. so the efficiency of a synchronization operation is bounded by the cost of mutex lock/unlock, not by condition wait. and note: in the usual case, there is no context switch at all. ๐
this is not to say that the efficiency of condition waiting is unimportant โ since there needs to be at least one context switch per Ada rendezvous, the efficiency of waiting on a condition variable matters. the cost of waiting on a condition variable should be little more than the minimal cost for a context switch plus the time to unlock and lock the mutex.
๐ Features of Mutexes and Condition Variables ๐
it had been suggested that mutex acquisition and release be decoupled from condition wait. this was rejected, bestie. because it is the combined nature of the operation that, in fact, facilitates realtime implementations. those implementations can atomically move a high-priority thread between the condition variable and the mutex in a manner that is transparent to the caller.
this can prevent extra context switches and provide more deterministic acquisition of a mutex when the waiting thread is signaled. so fairness and priority issues can be dealt with directly by the scheduling discipline. also? the current condition wait operation matches existing practice. slay.
๐๏ธ Scheduling Behavior of Mutexes and Condition Variables ๐๏ธ
synchronization primitives that try to interfere with scheduling policy by specifying an ordering rule are considered undesirable. threads waiting on mutexes and condition variables are selected to proceed in an order dependent upon the scheduling policy rather than in some fixed order (for example, FIFO or priority). so the scheduling policy decides which thread(s) get awakened and allowed to proceed. the policy is the main character here. ๐
โณ Timed Condition Wait โณ
the pthread_cond_timedwait() function lets an application give up waiting for a particular condition after a given amount of time. an example of its use follows:
(void) pthread_mutex_lock(&t.mn);
t.waiters++;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 5;
rc = 0;
while (! mypredicate(&t) && rc == 0)
rc = pthread_cond_timedwait(&t.cond, &t.mn, &ts);
t.waiters--;
if (rc == 0 || mypredicate(&t))
setmystate(&t);
(void) pthread_mutex_unlock(&t.mn);
by making the timeout parameter absolute, it doesn't need to be recomputed each time the program checks its blocking predicate. if the timeout was relative, it would have to be recomputed before each call โ and that would be especially difficult, since such code would need to take into account the possibility of extra wakeups that result from extra broadcasts or signals on the condition variable occurring before either the predicate is true or the timeout is due. exhausting honestly. ๐ญ
๐ฎ FUTURE DIRECTIONS ๐ฎ
None.
like... nothing. nada. the future is empty. ๐โจ
๐ SEE ALSO ๐
pthread_cond_broadcast()
the Base Definitions volume of POSIX.1โ2017, Section 4.12, Memory Synchronization, <pthread.h>
๐ COPYRIGHT ๐
portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. in the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. the original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. to report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
okay that's the whole page bestie, we made it ๐ซถ this one's from IEEE/The Open Group, 2017 โ go forth and re-check your predicates, always. no cap. ๐โจ๐๐ฆ
๐ฆ where this page comes from
- alpine 3.22: man-pages-posix 2017a-r0 ยท custom
- alpine 3.23: man-pages-posix 2017a-r0 ยท custom
- alpine 3.24: man-pages-posix 2017a-r0 ยท custom
- arch rolling: man-pages 6.19-1
- arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages-posix 2017a
- opensuse-leap 16.0: man-pages-posix 2017a-160000.4.1 ยท SUSE-IEEE
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms