CKTIS / C
cnd_timedwait — función de variable de condición de C23
`cnd_timedwait(cond, mtx, ts)` desbloquea atómicamente el `mtx` poseído y espera señal/broadcast, la hora civil absoluta `TIME_UTC` de `*ts` o un desbloqueo por motivo no especificado. Antes del retorno normal vuelve a bloquear el mutex.
Versión: C23
Sintaxis
int cnd_timedwait(cnd_t *restrict cond, mtx_t *restrict mtx, const struct timespec *restrict ts);cnd_timedwait(cond, mtx, ts) desbloquea atómicamente el mtx poseído y espera señal/broadcast, la hora civil absoluta TIME_UTC de *ts o un desbloqueo por motivo no especificado. Antes del retorno normal vuelve a bloquear el mutex.
El ejemplo bloquea el mutex, crea un instante un segundo en el pasado y llama realmente a cnd_timedwait sin señal. 1 1 significa thrd_timedout y mtx_unlock correcto, demostrando que el llamador vuelve a poseer el mutex tras timeout.
El llamador ya debe poseer mtx; *ts es una fecha límite TIME_UTC, no una duración relativa. Comprueba thrd_success, thrd_timedout y thrd_error, y tras éxito o timeout reevalúa el predicado en bucle, pues despertar —también por motivo no especificado— no vuelve verdadera la condición.
Ejemplos
#include <stdio.h>
#include <threads.h>
#include <time.h>
int main(void) {
mtx_t mutex;
cnd_t condition;
if (mtx_init(&mutex, mtx_plain) != thrd_success) return 1;
if (cnd_init(&condition) != thrd_success) return 1;
struct timespec deadline;
if (timespec_get(&deadline, TIME_UTC) != TIME_UTC) return 1;
if (deadline.tv_sec > 0) deadline.tv_sec -= 1;
if (mtx_lock(&mutex) != thrd_success) return 1;
int result = cnd_timedwait(&condition, &mutex, &deadline);
int unlocked = mtx_unlock(&mutex);
printf("%d %d\n", result == thrd_timedout, unlocked == thrd_success);
cnd_destroy(&condition);
mtx_destroy(&mutex);
return 0;
}
Resultado
1 1
El ejemplo bloquea el mutex, crea un instante un segundo en el pasado y llama realmente a `cnd_timedwait` sin señal. `1 1` significa `thrd_timedout` y `mtx_unlock` correcto, demostrando que el llamador vuelve a poseer el mutex tras timeout.