typestar

Condition variables in C

A thread waits until another signals that the state it needs has arrived.

#include <pthread.h>

typedef struct {
    int ready;
    pthread_mutex_t lock;
    pthread_cond_t cond;
} Gate;

void gate_init(Gate *g) {
    g->ready = 0;
    pthread_mutex_init(&g->lock, NULL);
    pthread_cond_init(&g->cond, NULL);
}

void gate_wait(Gate *g) {
    pthread_mutex_lock(&g->lock);
    while (!g->ready) {
        pthread_cond_wait(&g->cond, &g->lock);
    }
    pthread_mutex_unlock(&g->lock);
}

void gate_open(Gate *g) {
    pthread_mutex_lock(&g->lock);
    g->ready = 1;
    pthread_cond_broadcast(&g->cond);
    pthread_mutex_unlock(&g->lock);
}

How it works

  1. pthread_cond_wait releases the mutex while it waits.
  2. The wait must sit inside a loop, because wakeups can be spurious.
  3. signal wakes one waiter, broadcast wakes them all.

Keywords and builtins used here

The run, in numbers

Lines
28
Characters to type
505
Tokens
151
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 86 seconds.

Type this snippet

Step 4 of 4 in Locking, step 7 of 10 in Threads & concurrency.

← Previous Next →