typestar

Mutexes in C

A mutex serializes access, so two threads never update the counter at once.

#include <pthread.h>

typedef struct {
    long count;
    pthread_mutex_t lock;
} Counter;

void counter_init(Counter *c) {
    c->count = 0;
    pthread_mutex_init(&c->lock, NULL);
}

void counter_add(Counter *c, long n) {
    pthread_mutex_lock(&c->lock);
    c->count += n;
    pthread_mutex_unlock(&c->lock);
}

long counter_read(Counter *c) {
    pthread_mutex_lock(&c->lock);
    long value = c->count;
    pthread_mutex_unlock(&c->lock);
    return value;
}

void counter_destroy(Counter *c) {
    pthread_mutex_destroy(&c->lock);
}

How it works

  1. Lock, touch the shared state, unlock — keep the region small.
  2. Every return path must unlock, or the next thread waits forever.
  3. Without the lock the increment is a read, an add and a write.

Keywords and builtins used here

The run, in numbers

Lines
28
Characters to type
492
Tokens
136
Three-star pace
105 tpm

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

Type this snippet

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

← Previous Next →

Mutexes in other languages