Course contentsShow
← C
Lesson 1126 of 1,21915. Systems ProgrammingFree lesson

Locking and unlocking mutexes

Locking and unlocking mutexes

What you'll learn: How to use mutexes to ensure only one thread at a time can access a specific section of code.

The Bathroom Key Analogy

Imagine a busy coffee shop with a single-occupancy bathroom. To keep things orderly, the shop uses a key attached to a heavy wooden block. If you want to use the bathroom, you must first grab the key from the counter. While you are inside, no one else can enter because you have the only key. When you finish, you put the key back on the counter, making it available for the next person.

In C programming, a Mutex (short for Mutual Exclusion) is that key. When multiple threads are running, they might all try to update the same global variable at once, leading to a "race condition" where data gets corrupted. A mutex prevents this by forcing threads to wait their turn.

Lock and Unlock

To protect a piece of code, we use two primary functions from the pthread library:

  1. pthread_mutex_lock(): The thread attempts to grab the key. If another thread already has it, this thread will "sleep" and wait right there until the key is returned.
  2. pthread_mutex_unlock(): The thread puts the key back, waking up any other threads that are waiting for it.

The code between these two functions is called the Critical Section.

Implementation in C

Here is how you wrap a sensitive operation—like incrementing a shared counter—inside a mutex:

#include <pthread.h>

int counter = 0;
pthread_mutex_t my_mutex;

void* increment_counter(void* arg) {
    // 1. Attempt to grab the key
    pthread_mutex_lock(&my_mutex);

    // 2. CRITICAL SECTION: Only one thread can be here at a time
    counter++; 

    // 3. Put the key back for others
    pthread_mutex_unlock(&my_mutex);

    return NULL;
}

If you forget to lock, you risk data corruption. If you forget to unlock, your program will "deadlock," meaning every other thread will wait forever for a key that never returns to the counter. Always ensure every lock has a matching unlock.

Key takeaway

Use pthread_mutex_lock before accessing shared data and pthread_mutex_unlock immediately after to ensure thread safety.