CKTIS / C
cnd_broadcast — C23-conditievariabelefunctie
`cnd_broadcast(cond)` uit `<threads.h>` deblokkeert alle threads die op het moment van aanroepen op die conditievariabele wachten. Zonder wachtenden doet de functie niets; ze retourneert `thrd_success` of `thrd_error` als het verzoek niet kan worden uitgevoerd.
Versie: C23
Syntax
int cnd_broadcast(cnd_t *cond);cnd_broadcast(cond) uit <threads.h> deblokkeert alle threads die op het moment van aanroepen op die conditievariabele wachten. Zonder wachtenden doet de functie niets; ze retourneert thrd_success of thrd_error als het verzoek niet kan worden uitgevoerd.
Het voorbeeld start twee wachtenden; teller arrived en dezelfde mutex verzekeren dat beide de wachtfase bereikten. De hoofdthread zet predicaat open en roept cnd_broadcast aan; na join bevestigt 1 2 succes en doorgang van beide threads.
Een melding wordt niet onthouden, dus broadcast vóór het wachten helpt een latere wachtende niet. Elke gewekte thread moet de mutex meestal één voor één herverwerven en het predicaat in een lus controleren, omdat C23 deblokkering om ongespecificeerde reden toestaat; cond moet een levend, succesvol geïnitialiseerd object zijn.
Voorbeelden
#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;
}
Resultaat
1 2
Het voorbeeld start twee wachtenden; teller `arrived` en dezelfde mutex verzekeren dat beide de wachtfase bereikten. De hoofdthread zet predicaat `open` en roept `cnd_broadcast` aan; na join bevestigt `1 2` succes en doorgang van beide threads.