pthread_mutex
- C course
- Advanced
- Lesson 21/83
- 5 min
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.
Practice 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);.
Starter code
#include <stdio.h>
#include <pthread.h>
int counter = 0;
pthread_mutex_t lock;
// Write worker function (protect with mutex)
// Create two threads and join
// Print counter
int main(void) {
return 0;
}Sample 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;
}Expected output
counter=2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Mutex lock
pthread_mutex_____(&lock);
pthread_mutex_lock(&lock);
Explanation: pthread_mutex_lock acquires the lock.
2 Match mutex functions
| Term | Meaning |
|---|---|
pthread_mutex_lock |
Acquires lock |
pthread_mutex_unlock |
Releases lock |
pthread_mutex_init |
Initializes lock |
critical section |
Critical region |
3 What is a mutex used for?
- Protecting critical regions Correct answer
- Creating threads
- Sending signals
- Allocating memory
Explanation: A mutex protects the critical region and prevents data races.