CKTIS / C
cnd_broadcast — función de variable de condición de C23
`cnd_broadcast(cond)` de `<threads.h>` desbloquea todos los hilos bloqueados en esa variable de condición en el momento de la llamada. Sin esperas no hace nada; devuelve `thrd_success` o `thrd_error` si no puede atender la solicitud.
Versión: C23
Sintaxis
int cnd_broadcast(cnd_t *cond);cnd_broadcast(cond) de <threads.h> desbloquea todos los hilos bloqueados en esa variable de condición en el momento de la llamada. Sin esperas no hace nada; devuelve thrd_success o thrd_error si no puede atender la solicitud.
El ejemplo inicia dos hilos en espera; el contador arrived y el mismo mutex garantizan que ambos llegaron a esperar. El hilo principal fija el predicado open y llama a cnd_broadcast; tras join, 1 2 confirma éxito y que ambos avanzaron.
La notificación no se recuerda, de modo que un broadcast anterior no ayuda a quien espere después. Cada hilo despertado debe readquirir el mutex, normalmente uno a uno, y comprobar el predicado en bucle porque C23 permite desbloqueo por motivo no especificado; cond debe ser un objeto vivo creado por cnd_init correcto.
Ejemplos
#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;
}
Resultado
1 2
El ejemplo inicia dos hilos en espera; el contador `arrived` y el mismo mutex garantizan que ambos llegaron a esperar. El hilo principal fija el predicado `open` y llama a `cnd_broadcast`; tras join, `1 2` confirma éxito y que ambos avanzaron.