2.3. cond — Condition variable

A condition variable is a synchronization primitive used to unblock zero, one or all thread(s) waiting for the condition variable.

2.3.1. Example usage

This is a small example of signalling a waiting thread.

struct cond_t cond;
struct mutex_t mutex;
int resource = 0;

/* Initialize the condition variable and a mutex. */
cond_init(&cond);
mutex_init(&mutex);

/* This thread waits for a signal from the signaller thread. */
void *waiter_main()
{
    mutex_lock(&mutex);
    cond_wait(&cond, &mutex, NULL)
    mutex_unlock(&mutex);
}

/* This thread signals the waiter thread. */
void *signaller_main()
{
    /* The mutex is optional when signalling a condition. */
    mutex_lock(&mutex);
    cond_signal(&cond)
    mutex_unlock(&mutex);
}

Source code: src/sync/cond.h, src/sync/cond.c

Test code: tst/sync/cond/main.c

Test coverage: src/sync/cond.c


Functions

int cond_module_init(void)

Initialize the condition variable module. This function must be called before calling any other function in this module.

The module will only be initialized once even if this function is called multiple times.

Return
zero(0) or negative error code

int cond_init(struct cond_t *self_p)

Initialize given condition variable object.

Return
zero(0) or negative error code.
Parameters
  • self_p: Condition variable to initialize.

int cond_wait(struct cond_t *self_p, struct mutex_t *mutex_p, struct time_t *timeout_p)

Wait until given condition variable is unblocked or an timeout occurs. Given mutex must be locked when this function is called, and it is still locked when this function returns.

Return
zero(0) or negative error code.
Parameters
  • self_p: Condition variable to wait for.
  • mutex_p: Mutex.

int cond_signal(struct cond_t *self_p)

Unblock one thread waiting on given condition variable. This function is a no-op if no threads are waiting on given condition variable.

Return
One(1) if a thread was unblocked, zero(0) if no thread was unblocked, or negative error code.
Parameters
  • self_p: Condition variable.

int cond_broadcast(struct cond_t *self_p)

Unblock all threads waiting on given condition variable.

Return
Number of unblocked threads or negative error code.
Parameters
  • self_p: Condition variable.

struct cond_t

Public Members

struct thrd_prio_list_t waiters

Wait list.