C
pthread_mutex
Learn mutual exclusion with pthread_mutex.
pthread_mutex
A mutex (mutual exclusion) is a lock that serializes access to shared data. Only one thread enters the locked region at a time.
First declare pthread_mutex_t lock; and initialize with pthread_mutex_init(&lock, NULL). Before the critical region call pthread_mutex_lock(&lock), after it pthread_mutex_unlock(&lock). The code in between runs in only one thread. When done, clean up with pthread_mutex_destroy(&lock).
Critical region
A critical region is a piece of code that accesses shared data. If multiple threads enter at once, a data race occurs; the result is unpredictable.
For example, counter++ is actually read-increment-write steps. If two threads interleave, one update can be lost. With a mutex you lock the region: lock, increment counter, unlock. Each increment becomes complete and ordered.
Exercise Counter with two threads
Declare global int counter = 0; and pthread_mutex_t lock;. Write void *worker(void *arg) with pthread_mutex_lock(&lock); counter++; pthread_mutex_unlock(&lock);. Initialize with pthread_mutex_init(&lock, NULL);. Create two threads, join them and print printf("counter=%d\n", counter);.
Show example solution
#include <stdio.h>
#include <pthread.h>
int counter = 0;
pthread_mutex_t lock;
void *worker(void *arg) {
pthread_mutex_lock(&lock);
counter++;
pthread_mutex_unlock(&lock);
return NULL;
}
int main(void) {
pthread_mutex_init(&lock, NULL);
pthread_t t1, t2;
pthread_create(&t1, NULL, worker, NULL);
pthread_create(&t2, NULL, worker, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("counter=%d\n", counter);
return 0;
}
Test yourself
-
Mutex lock
pthread_mutex_____(&lock);
Show answer
pthread_mutex_lock(&lock);
-
Match mutex functions
- pthread_mutex_lock
- Acquires lock
- pthread_mutex_unlock
- Releases lock
- pthread_mutex_init
- Initializes lock
- critical section
- Critical region
-
What is a mutex used for?
- Protecting critical regions
- Creating threads
- Sending signals
- Allocating memory
Show answer
Protecting critical regions — A mutex protects the critical region and prevents data races.
Next lesson: pthread_cond