C
Deadlock
Learn the deadlock concept and how to prevent it.
What is deadlock?
Deadlock is a stalemate where two or more processes wait for locks held by each other. Process A locks X, process B locks Y; A waits for Y, B waits for X. Neither can proceed and the program hangs.
Deadlock occurs when four conditions hold at once: mutual exclusion, hold-and-wait, no preemption, circular wait. The most common prevention is lock ordering: all processes take locks in the same order. First a, then b; never first b, then a. This breaks the cycle. Non-blocking calls like F_SETLK and the LOCK_NB flag also provide escape.
Ordered lock pattern
When two file locks are needed, keep the order fixed. First lock file a, then file b. Release in reverse order: first b, then a. This prevents another process from taking locks in a different order and causing deadlock.
For testing, open two files and lock in order: int a = open("/tmp/cb_a.txt", O_CREAT | O_RDWR, 0644); int b = open("/tmp/cb_b.txt", O_CREAT | O_RDWR, 0644);. Take with flock(a, LOCK_EX); flock(b, LOCK_EX); and print printf("ordered\n");. Release: flock(b, LOCK_UN); flock(a, LOCK_UN);. Finally clean with close and unlink.
Exercise Take locks in order
Open two files with int a = open("/tmp/cb_a.txt", O_CREAT | O_RDWR, 0644); and int b = open("/tmp/cb_b.txt", O_CREAT | O_RDWR, 0644);. Take locks in order with flock(a, LOCK_EX); flock(b, LOCK_EX);. printf("ordered\n");. Release with flock(b, LOCK_UN); flock(a, LOCK_UN);. close(a); close(b); and unlink("/tmp/cb_a.txt"); unlink("/tmp/cb_b.txt");.
Show example solution
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
int main(void) {
int a = open("/tmp/cb_a.txt", O_CREAT | O_RDWR, 0644);
int b = open("/tmp/cb_b.txt", O_CREAT | O_RDWR, 0644);
flock(a, LOCK_EX);
flock(b, LOCK_EX);
printf("ordered\n");
flock(b, LOCK_UN);
flock(a, LOCK_UN);
close(a);
close(b);
unlink("/tmp/cb_a.txt");
unlink("/tmp/cb_b.txt");
return 0;
}
Test yourself
-
What is the most common way to prevent deadlock?
- Take more locks
- Never release locks
- Use only shared locks
- Lock ordering
Show answer
Lock ordering — Lock ordering breaks circular wait.
-
Match deadlock concepts
- Mutual exclusion
- Single owner
- Hold and wait
- Grab then wait
- Circular wait
- Cycle
- Lock ordering
- Prevention
-
First lock
flock(____, LOCK_EX);
Show answer
flock(a, LOCK_EX);
Next lesson: Automatic cleanup