Sub topic 5
The Critical-Section Problem
Prerequisites and the shared-data hazard
This chapter assumes that you understand processes, threads, context switches, and basic C-like code. A critical section is the part of a program that accesses shared data or a shared resource. Only one thread or process should execute that part at a time when simultaneous access could produce an incorrect result.
A race condition occurs when the result depends on the timing of concurrent operations. For example, suppose two threads execute:
counter = counter + 1This statement looks like one operation, but it usually contains several steps:
- Read
counter. - Add one.
- Write the new value.
If counter starts at 0, this interleaving is possible:
| Step | Thread 1 | Thread 2 | Counter |
|---|---|---|---|
| 1 | Reads 0 | 0 | |
| 2 | Reads 0 | 0 | |
| 3 | Writes 1 | 1 | |
| 4 | Writes 1 | 1 |
The expected result is 2, but the final value is 1. The update from one thread has been lost.
Protecting a critical section
A synchronization solution controls entry to the critical section. The following complete C program uses a mutex, a lock that allows only one thread to enter the protected region.
#include <pthread.h>
#include <stdio.h>
enum { THREADS = 2, UPDATES = 100000 };
int counter = 0;
pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER;
void *worker(void *argument) {
(void)argument;
for (int i = 0; i < UPDATES; i++) {
pthread_mutex_lock(&counter_lock);
counter++;
pthread_mutex_unlock(&counter_lock);
}
return NULL;
}
int main(void) {
pthread_t threads[THREADS];
for (int i = 0; i < THREADS; i++)
pthread_create(&threads[i], NULL, worker, NULL);
for (int i = 0; i < THREADS; i++)
pthread_join(threads[i], NULL);
printf("counter = %d\n", counter);
pthread_mutex_destroy(&counter_lock);
return 0;
}Compile it with:
cc -pthread counter.c -o counterThe lock protects the read-modify-write operation. Therefore, the program prints counter = 200000. Removing the lock makes the program vulnerable to a race condition.
The three requirements
A correct critical-section solution must satisfy these requirements:
| Requirement | Meaning |
|---|---|
| Mutual exclusion | At most one process is inside the critical section at a time. |
| Progress | If the section is empty and some processes want to enter, one of them can proceed. |
| Bounded waiting | A process will not wait forever while others repeatedly enter first. |
A solution that provides mutual exclusion but allows one process to be postponed indefinitely has a starvation problem. A solution that makes every process wait forever has failed progress.
Exercise
Exercise
Two processes both execute x = x + 1, and x starts at 5. What incorrect final value can result, and which requirement prevents it?
Show answer
The final value can be 6 instead of 7 because both processes may read 5 before either writes. Mutual exclusion prevents this lost update.