Sub topic 5
The critical-section problem
This chapter assumes you know what a race condition is, how the scheduler can preempt a process between any two instructions, and how to read C-like pseudocode. It defines the critical-section problem and shows why simple fixes fail. The next chapter states the formal requirements for a correct solution.
From race condition to critical section
A race condition happens when the result depends on how the scheduler interleaves operations on shared data. The cause is that an operation such as count++ is not one step. It compiles to a load, an add and a store, and a context switch can fall between any two of them.
The fix is to make sure only one process at a time runs the code that touches the shared data. That code is the critical section: a segment of code that accesses a shared resource (a variable, a file, a table) and must not be executed by more than one process at the same time.
Two points are easy to get wrong:
- A critical section is a property of the code, but the problem it creates comes from the data. Two different code fragments that update the same shared variable are both critical sections for that variable.
- Code that only touches local variables is never a critical section. Each process has its own copy, so nothing is shared.
The structure of a participating process
Every process that shares data with others is written in four parts:
- Entry section: requests permission to enter.
- Critical section: the code that touches the shared data.
- Exit section: announces that the process has left.
- Remainder section: everything else the process does.
while (1) {
/* entry section */
/* critical section */
/* exit section */
/* remainder section */
}The critical-section problem is to design the entry and exit sections, which is the protocol. The critical section itself is whatever the programmer needs to protect.
A runnable example
The program below has two threads that each add 100000 to a shared counter. The pthread_mutex_lock call is the entry section and pthread_mutex_unlock is the exit section. Compile with gcc file.c -pthread.
#include <pthread.h>
#include <stdio.h>
static long counter = 0;
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static void *worker(void *arg) {
(void)arg;
for (int i = 0; i < 100000; i++) {
pthread_mutex_lock(&m); /* entry section */
counter++; /* critical section */
pthread_mutex_unlock(&m); /* exit section */
}
return NULL;
}
int main(void) {
pthread_t a, b;
pthread_create(&a, NULL, worker, NULL);
pthread_create(&b, NULL, worker, NULL);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("counter = %ld\n", counter);
return 0;
}With the mutex, the output is always counter = 200000. If you delete the lock and unlock lines, the result is usually smaller and changes between runs. The lost updates are the interleaving problem from the previous chapter.
Where critical sections occur in an operating system
The kernel is full of shared data: the ready queue, the list of open files, memory-allocation tables, process tables. Two processes calling fork() at once could be handed the same process ID if the ID counter were unprotected.
How the kernel handles this depends on whether it can be preempted:
| Kernel type | Can a process be preempted while in kernel mode? | Race risk on kernel data |
|---|---|---|
| Non-preemptive | No. It runs until it exits kernel mode, blocks or yields. | Low on a single CPU, since only one kernel path runs at a time. |
| Preemptive | Yes. | Higher. Kernel data needs explicit protection. |
A non-preemptive kernel on a uniprocessor is free of kernel race conditions almost by construction. On multiprocessors even a non-preemptive kernel has races, because two CPUs run kernel code at the same instant. Preemptive kernels are harder to design but respond better to real-time processes, because a high-priority process does not wait for a long kernel path to finish.
Two tempting fixes that do not work
Disabling interrupts
On a single CPU, a process could turn off interrupts on entry and turn them back on at exit. With no timer interrupt, no preemption can occur inside the critical section. This is used inside kernels for very short sections, but it is not a general answer:
- On a multiprocessor, disabling interrupts affects only one CPU. Another CPU still enters the critical section.
- Giving user programs this power is dangerous. A program that forgets to re-enable interrupts hangs the machine.
- The clock and other devices stop being serviced, so the system loses time and responsiveness.
A single shared lock flag
The second idea is a shared variable that says whether someone is inside.
int lock = 0; /* 0 = free, 1 = taken */
void enter_region(void) {
while (lock == 1)
; /* wait */
lock = 1; /* take it */
}
void leave_region(void) {
lock = 0;
}This looks right but fails. Checking lock and setting lock are two separate steps. Here is one bad interleaving:
| Step | P0 | P1 | lock |
|---|---|---|---|
| 1 | reads `lock`, sees 0, exits the loop | 0 | |
| 2 | (preempted) | reads `lock`, sees 0, exits the loop | 0 |
| 3 | sets `lock = 1`, enters critical section | 1 | |
| 4 | sets `lock = 1`, enters critical section | 1 |
Both processes are now inside. The lock is itself shared data with a race condition, so the protocol has the same problem it was meant to solve. A correct protocol must make the test and the set behave as one indivisible step, or must avoid needing that. Peterson's algorithm and the hardware instructions are the two ways to do it, and they come in later chapters.
Strict alternation
A third attempt uses a shared turn variable that says whose turn it is. Process 0 enters only when turn == 0 and then sets turn = 1 on exit. Process 1 does the mirror image. Both can never be inside together, so this works in that narrow sense. It fails differently: the processes are forced to take turns. If process 0 is in a long remainder section and process 1 wants to enter twice in a row, process 1 waits for a process that is not even interested in the critical section. A process outside its critical section is blocking another one.
The three attempts fail in three different ways:
- Disabling interrupts fails on multiple CPUs and is unsafe for user code.
- The lock flag permits two processes inside at once.
- Strict alternation makes an uninterested process hold up an interested one.
These are the three failure types that the formal requirements are designed to rule out. The next chapter names them: mutual exclusion, progress and bounded waiting.
Assumptions behind the textbook problem
The classic statement of the problem makes several assumptions, and GATE questions rely on them:
- Each process runs at nonzero speed, but nothing is assumed about the relative speeds of processes.
- Nothing is assumed about the number of CPUs.
- Basic machine instructions such as a single load or a single store are atomic. A statement such as
count++is not. - A process stays in its critical section for a finite time, and it does not crash inside it.
The speed assumption matters most. A correct solution must work for every possible interleaving, not just the likely ones. To show that a protocol is wrong, one bad interleaving is enough, as in the table above. To show it is right, you must argue about all of them.
Common errors
- Treating
count++as one step. It is a read-modify-write sequence. - Protecting only the writers. If a reader can see a half-updated structure, reads belong in a critical section too.
- Making the critical section too large. Holding a lock during slow work, such as disk I/O, serialises everything. Keep it to the shared access.
- Using different locks for the same data. Two processes holding different locks do not exclude each other.
- Calling a protocol correct after testing it. A race may need a one-in-a-million interleaving.
Exercise
Two processes share the variable x, initially 0. Each runs the code x = x + 1 once, protected by the single-flag protocol (while (lock == 1); lock = 1; ... lock = 0;). Give one interleaving, in terms of the lock checks and sets, in which the protocol lets both processes into the critical section at once. Why does this happen?
Show answer
P0 reads lock and sees 0, then is preempted before setting it. P1 reads lock, sees 0, sets lock to 1 and enters. P0 resumes, sets lock to 1 and also enters. Both are inside at once. The test of the flag and the set of the flag are separate steps, so the lock variable is itself a shared variable with a race condition.
Exercise
A kernel is non-preemptive and runs on a single CPU. Is a race condition on a kernel data structure possible? What changes if the machine has two CPUs?
Show answer
On one CPU it is essentially not possible, because a process in kernel mode runs until it leaves kernel mode, blocks or yields, so no other kernel path interleaves with it. With two CPUs, kernel code runs on both at the same time, so a race on shared kernel data is possible even though neither path is preempted.