Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

cnd_init — C23 condition-variable function

`cnd_init(cond)` creates a new condition variable and, on success, stores in `*cond` a value that uniquely identifies it. It returns `thrd_success`, `thrd_nomem` when memory cannot be allocated, or `thrd_error` when the request cannot be honored.

Version: C23

Syntax

int cnd_init(cnd_t *cond);

cnd_init(cond) creates a new condition variable and, on success, stores in *cond a value that uniquely identifies it. It returns thrd_success, thrd_nomem when memory cannot be allocated, or thrd_error when the request cannot be honored.

The example checks the initialization result before using the object, then calls cnd_signal with no waiters—which must succeed—and safely destroys the condition. Output 1 1 confirms both success codes.

After failure, do not use or destroy the contents of *cond as a valid condition variable. A newly created condition has no stored “signalled” state: a waiter blocks until a later signal or an unblock for an unspecified reason; use the same initialized object, not a bytewise copy as a second condition.

Examples

#include <stdio.h>
#include <threads.h>

int main(void) {
    cnd_t condition;
    int initialized = cnd_init(&condition);
    if (initialized != thrd_success) return 1;
    int signalled_without_waiters = cnd_signal(&condition);
    printf("%d %d\n", initialized == thrd_success, signalled_without_waiters == thrd_success);
    cnd_destroy(&condition);
    return 0;
}

Result

1 1

The example checks the initialization result before using the object, then calls `cnd_signal` with no waiters—which must succeed—and safely destroys the condition. Output `1 1` confirms both success codes.

Sources