CSE Roadmap

Core tier · about 4 hours · 7 parts

Part 3 of 7 · 2 min read

Mutex

In plain words: The fix is to make the three steps indivisible, so that no other thread can run its own three steps in the middle. A mutex (short for mutual exclusion, a lock that only one thread can hold at a time) does that. A thread calls pthread_mutex_lock before the update and pthread_mutex_unlock after. If another thread holds the lock, the caller waits.

static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static void *inc(void *a) {
    (void)a;
    for (int i = 0; i < N; i++) {
        pthread_mutex_lock(&lock);
        counter++;
        pthread_mutex_unlock(&lock);
    }
    return NULL;
}

Three runs of the changed program printed expected 2000000, got 2000000 each time. The part between lock and unlock is a critical section, a stretch of code that only one thread may run at a time. Level 4 explains how locks work inside and the many ways they go wrong, such as two threads waiting for each other for ever (Level 5).

Locks cost time. The unlocked program above took 0.007 seconds in a run, and the locked one took 0.17 seconds, about 25 times longer, since every increment now takes a lock and threads sometimes wait for each other. The result is correct, and the time shows why programs try to lock rarely and for short periods.

Mutex and critical section

A mutex is a lock that at most one thread can hold at a time; a thread that tries to take a held mutex waits until it is released. A critical section is the stretch of code between taking and releasing the lock, in which a thread may safely use the shared data.

Example: wrapping counter++ in pthread_mutex_lock and pthread_mutex_unlock makes the update atomic with respect to other threads that use the same mutex.

Check yourself: 1. What does a thread do when it calls pthread_mutex_lock on a mutex that is held? 2. Which lines form the critical section above? 3. Why is the locked program slower?