typestar

Read-write locks in C

Many readers together, or one writer alone.

#define _POSIX_C_SOURCE 200809L

#include <pthread.h>

typedef struct {
    int values[16];
    size_t count;
    pthread_rwlock_t lock;
} Table;

void table_init(Table *t) {
    t->count = 0;
    pthread_rwlock_init(&t->lock, NULL);
}

int table_append(Table *t, int value) {
    pthread_rwlock_wrlock(&t->lock);
    int ok = t->count < 16;
    if (ok) {
        t->values[t->count++] = value;
    }
    pthread_rwlock_unlock(&t->lock);
    return ok;
}

size_t table_size(Table *t) {
    pthread_rwlock_rdlock(&t->lock);
    size_t n = t->count;
    pthread_rwlock_unlock(&t->lock);
    return n;
}

How it works

  1. rdlock may be held by several threads at once.
  2. wrlock waits for every reader to leave.
  3. Both are released by the same unlock call.

Keywords and builtins used here

The run, in numbers

Lines
31
Characters to type
532
Tokens
152
Three-star pace
105 tpm

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

Type this snippet

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

← Previous Next →