Table of Contents

Mutex

Mutex (mutual exclusion lock) allows only one thread to hold it at a time; other threads block until the owner unlocks. A mutex enforces ownership: only the locking thread may unlock, protecting against bugs where the wrong thread releases it.

Use mutex for protecting short critical sections; spinlock is better for very short sections with low contention.

Example

This example shows mutex protecting a shared counter from race conditions.

// compile: gcc -pthread -o mutex mutex.c
// run: ./mutex
// description: mutex ensures exclusive access to critical section
 
#include <pthread.h>
#include <stdio.h>
 
int counter = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
 
void* increment(void* arg) {
    for (int i = 0; i < 1000000; i++) {
        pthread_mutex_lock(&lock);
        counter++;
        pthread_mutex_unlock(&lock);
    }
    return NULL;
}
 
int main() {
    pthread_t t1, t2;
    pthread_create(&t1, NULL, increment, NULL);
    pthread_create(&t2, NULL, increment, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    printf("Counter: %d (expected: 2000000)\n", counter);
    return 0;
}