CKTIS / C
cnd_broadcast — C23 condition-variable function
`cnd_broadcast(cond)` from `<threads.h>` unblocks every thread blocked on that condition variable at the time of the call. With no waiters it does nothing; it returns `thrd_success`, or `thrd_error` when the request cannot be honored.
Version: C23
Syntax
int cnd_broadcast(cnd_t *cond);cnd_broadcast(cond) from <threads.h> unblocks every thread blocked on that condition variable at the time of the call. With no waiters it does nothing; it returns thrd_success, or thrd_error when the request cannot be honored.
The example starts two waiters, and the arrived counter plus the same mutex ensure both have entered the wait. The main thread sets the open predicate and calls cnd_broadcast; after joining, 1 2 confirms success and that both threads passed.
A notification is not remembered, so broadcasting before a wait does not help a later waiter. Every awakened thread must reacquire the mutex, normally one at a time, and recheck the predicate in a loop because C23 permits unblocking for an unspecified reason; cond must be a live object produced by successful cnd_init.
Examples
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>
static mtx_t gate;
static cnd_t condition;
static atomic_int arrived;
static atomic_int awakened;
static int open;
static int waiter(void *unused) {
(void)unused;
if (mtx_lock(&gate) != thrd_success) return 1;
atomic_fetch_add(&arrived, 1);
while (!open) {
if (cnd_wait(&condition, &gate) != thrd_success) {
mtx_unlock(&gate);
return 1;
}
}
atomic_fetch_add(&awakened, 1);
return mtx_unlock(&gate) == thrd_success ? 0 : 1;
}
int main(void) {
if (mtx_init(&gate, mtx_plain) != thrd_success) return 1;
if (cnd_init(&condition) != thrd_success) {
mtx_destroy(&gate);
return 1;
}
thrd_t first;
thrd_t second;
if (thrd_create(&first, waiter, NULL) != thrd_success) return 1;
if (thrd_create(&second, waiter, NULL) != thrd_success) {
mtx_lock(&gate);
open = 1;
cnd_broadcast(&condition);
mtx_unlock(&gate);
thrd_join(first, NULL);
return 1;
}
while (atomic_load(&arrived) != 2) thrd_yield();
if (mtx_lock(&gate) != thrd_success) return 1;
open = 1;
int result = cnd_broadcast(&condition);
if (mtx_unlock(&gate) != thrd_success) return 1;
int first_result;
int second_result;
thrd_join(first, &first_result);
thrd_join(second, &second_result);
printf("%d %d\n", result == thrd_success && first_result == 0 && second_result == 0,
atomic_load(&awakened));
cnd_destroy(&condition);
mtx_destroy(&gate);
return 0;
}
Result
1 2
The example starts two waiters, and the `arrived` counter plus the same mutex ensure both have entered the wait. The main thread sets the `open` predicate and calls `cnd_broadcast`; after joining, `1 2` confirms success and that both threads passed.