CKTIS / C
cnd_timedwait — C23 condition-variable function
`cnd_timedwait(cond, mtx, ts)` atomically unlocks the owned `mtx` and waits for a signal/broadcast, the absolute `TIME_UTC` calendar time in `*ts`, or an unblock for an unspecified reason. Before a normal return it locks that mutex again.
Version: C23
Syntax
int cnd_timedwait(cnd_t *restrict cond, mtx_t *restrict mtx, const struct timespec *restrict ts);cnd_timedwait(cond, mtx, ts) atomically unlocks the owned mtx and waits for a signal/broadcast, the absolute TIME_UTC calendar time in *ts, or an unblock for an unspecified reason. Before a normal return it locks that mutex again.
The example locks the mutex, creates a time point one second in the past, and genuinely calls cnd_timedwait without a signal. Output 1 1 means thrd_timedout and a successful mtx_unlock, demonstrating that the caller owns the mutex again after timeout.
The caller must already own mtx; *ts is a TIME_UTC deadline, not a relative duration. Check thrd_success, thrd_timedout, and thrd_error, and after success or timeout re-evaluate the predicate in a loop because waking—including for an unspecified reason—does not make the condition true.
Examples
#include <stdio.h>
#include <threads.h>
#include <time.h>
int main(void) {
mtx_t mutex;
cnd_t condition;
if (mtx_init(&mutex, mtx_plain) != thrd_success) return 1;
if (cnd_init(&condition) != thrd_success) return 1;
struct timespec deadline;
if (timespec_get(&deadline, TIME_UTC) != TIME_UTC) return 1;
if (deadline.tv_sec > 0) deadline.tv_sec -= 1;
if (mtx_lock(&mutex) != thrd_success) return 1;
int result = cnd_timedwait(&condition, &mutex, &deadline);
int unlocked = mtx_unlock(&mutex);
printf("%d %d\n", result == thrd_timedout, unlocked == thrd_success);
cnd_destroy(&condition);
mtx_destroy(&mutex);
return 0;
}
Result
1 1
The example locks the mutex, creates a time point one second in the past, and genuinely calls `cnd_timedwait` without a signal. Output `1 1` means `thrd_timedout` and a successful `mtx_unlock`, demonstrating that the caller owns the mutex again after timeout.