CKTIS / C
cnd_signal — fonction de variable de condition C23
`cnd_signal(cond)` débloque un thread bloqué sur `cond` au moment de l’appel. Sans attente, elle ne fait rien et renvoie quand même `thrd_success` ; sinon le résultat est `thrd_success` ou `thrd_error`.
Version : C23
Syntaxe
int cnd_signal(cnd_t *cond);cnd_signal(cond) débloque un thread bloqué sur cond au moment de l’appel. Sans attente, elle ne fait rien et renvoie quand même thrd_success ; sinon le résultat est thrd_success ou thrd_error.
Dans l’exemple, waiting et le mutex partagé garantissent qu’un worker attend réellement. Le thread principal écrit payload = 42 sous protection, fixe ready, appelle cnd_signal, puis affiche 1 42 après join.
Le choix parmi plusieurs attentes n’est pas garanti et un signal précoce n’est pas mis en file. Le signal ne remplace pas la protection des données : modifiez le prédicat sous le même mutex et attendez en boucle, car un thread peut être débloqué pour une raison non spécifiée.
Exemples
#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;
}
Résultat
1 42
Dans l’exemple, `waiting` et le mutex partagé garantissent qu’un worker attend réellement. Le thread principal écrit `payload = 42` sous protection, fixe `ready`, appelle `cnd_signal`, puis affiche `1 42` après join.