Course contentsShow
← Computer Science
Lesson 1283 of 2,87230. Process SynchronizationFree lesson

Pthread Mutex Basics

Introduction to POSIX thread mutexes: initialization, pthread_mutex_lock, and pthread_mutex_unlock functions.

Pthread Mutex Basics

You'll learn how to create and use POSIX thread mutexes to protect critical sections in multithreaded programs.

Now that you understand locks conceptually, let's see them in practice. Pthread mutexes (mutual exclusion objects) are the most common way to implement locks in C programs using the POSIX threads library. They give you the acquire/release lock semantics you need to protect critical sections from race conditions.

Initialization

Before using a mutex, you must initialize it. The simplest way is static initialization:

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

This creates a mutex named lock ready to use.

Locking and Unlocking

To protect a critical section, acquire the lock before entering and release it after exiting:

pthread_mutex_lock(&lock);    // Acquire: blocks if already held
// Critical section - only one thread at a time
pthread_mutex_unlock(&lock);  // Release: let other threads in

pthread_mutex_lock() is the acquire operation—if another thread holds the lock, the calling thread waits (blocks) until it's free. pthread_mutex_unlock() is the release operation—it frees the lock so another waiting thread can proceed.

Analogy

Think of the mutex as a single bathroom key. Only the person holding the key can enter (lock). When they're done, they return the key (unlock), and the next person waiting can take it.

Complete Example Pattern

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int shared_counter = 0;

// In thread function:
pthread_mutex_lock(&lock);
shared_counter++;  // Protected from race conditions
pthread_mutex_unlock(&lock);

Key Takeaway: Pthread mutexes implement locks using pthread_mutex_lock() to enter critical sections and pthread_mutex_unlock() to exit them, ensuring mutual exclusion and preventing race conditions on shared data.