CKTIS / C
cnd_signal — C23-conditievariabelefunctie
`cnd_signal(cond)` deblokkeert één thread die bij de aanroep op `cond` wacht. Zonder wachtenden doet de functie niets en retourneert toch `thrd_success`; anders is het resultaat `thrd_success` of `thrd_error`.
Versie: C23
Syntax
int cnd_signal(cnd_t *cond);cnd_signal(cond) deblokkeert één thread die bij de aanroep op cond wacht. Zonder wachtenden doet de functie niets en retourneert toch thrd_success; anders is het resultaat thrd_success of thrd_error.
Het voorbeeld gebruikt waiting en de gedeelde mutex om te verzekeren dat één worker werkelijk wacht. De hoofdthread schrijft beschermd payload = 42, zet ready, roept cnd_signal aan en drukt na join 1 42 af.
Welke van meerdere wachtenden wordt gekozen is niet gegarandeerd en een vroeg signaal wordt niet opgeslagen. Het signaal vervangt gegevensbescherming niet: wijzig het predicaat onder dezelfde mutex en wacht in een lus, want een thread kan om ongespecificeerde reden deblokkeren.
Voorbeelden
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>
static mtx_t gate;
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(&gate) != thrd_success) return 1;
atomic_store(&waiting, 1);
while (!ready) {
if (cnd_wait(&condition, &gate) != thrd_success) {
mtx_unlock(&gate);
return 1;
}
}
observed = payload;
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) return 1;
thrd_t thread;
if (thrd_create(&thread, worker, NULL) != thrd_success) return 1;
while (!atomic_load(&waiting)) thrd_yield();
if (mtx_lock(&gate) != thrd_success) return 1;
payload = 42;
ready = 1;
int result = cnd_signal(&condition);
if (mtx_unlock(&gate) != thrd_success) return 1;
int worker_result;
thrd_join(thread, &worker_result);
printf("%d %d\n", result == thrd_success && worker_result == 0, observed);
cnd_destroy(&condition);
mtx_destroy(&gate);
return 0;
}
Resultaat
1 42
Het voorbeeld gebruikt `waiting` en de gedeelde mutex om te verzekeren dat één worker werkelijk wacht. De hoofdthread schrijft beschermd `payload = 42`, zet `ready`, roept `cnd_signal` aan en drukt na join `1 42` af.