CKTIS / C
cnd_wait — C23 wait function
`cnd_wait(cond, mtx)` from `<threads.h>` atomically unlocks the owned `mtx` and blocks until a signal, broadcast, or an unblock for an unspecified reason. Before returning it locks `mtx` again; the result is `thrd_success` or `thrd_error`.
Version: C23
Syntax
int cnd_wait(cnd_t *cond, mtx_t *mtx);cnd_wait(cond, mtx) from <threads.h> atomically unlocks the owned mtx and blocks until a signal, broadcast, or an unblock for an unspecified reason. Before returning it locks mtx again; the result is thrd_success or thrd_error.
The example starts a worker that sets waiting, waits for the protected ready predicate, and reads payload after the signal. Output 1 42 confirms a successful cnd_wait, reacquisition of the mutex, and visibility of data protected by that same mutex.
The caller must already own mtx, and both pointers must designate live, correctly initialized objects. Notifications are not queued and waking does not prove the condition true, so test the predicate in a loop; after an error, do not consume protected data as though the wait had succeeded.
Examples
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>
static mtx_t mutex;
static cnd_t condition;
static atomic_int waiting;
static int ready;
static int payload;
static int observed;
static int worker(void *unused) {
(void)unused;
if (mtx_lock(&mutex) != thrd_success) return 1;
atomic_store(&waiting, 1);
while (!ready) {
if (cnd_wait(&condition, &mutex) != thrd_success) {
mtx_unlock(&mutex);
return 1;
}
}
observed = payload;
return mtx_unlock(&mutex) == thrd_success ? 0 : 1;
}
int main(void) {
if (mtx_init(&mutex, mtx_plain) != thrd_success) return 1;
if (cnd_init(&condition) != thrd_success) {
mtx_destroy(&mutex);
return 1;
}
thrd_t thread;
if (thrd_create(&thread, worker, NULL) != thrd_success) return 1;
while (!atomic_load(&waiting)) thrd_yield();
if (mtx_lock(&mutex) != thrd_success) return 1;
payload = 42;
ready = 1;
if (cnd_signal(&condition) != thrd_success) return 1;
if (mtx_unlock(&mutex) != thrd_success) return 1;
int worker_result;
if (thrd_join(thread, &worker_result) != thrd_success) return 1;
printf("%d %d\n", worker_result == 0, observed);
cnd_destroy(&condition);
mtx_destroy(&mutex);
return 0;
}
Result
1 42
The example starts a worker that sets `waiting`, waits for the protected `ready` predicate, and reads `payload` after the signal. Output `1 42` confirms a successful `cnd_wait`, reacquisition of the mutex, and visibility of data protected by that same mutex.