Deadlock
- C course
- Advanced
- Lesson 40/83
- 5 min
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.
Practice 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");.
Starter code
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
// Open two files
// Lock a, b in order and print
// Release b, a in order, close and remove
int main(void) {
return 0;
}Sample 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;
}Expected output
ordered
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the most common way to prevent deadlock?
- Take more locks
- Never release locks
- Use only shared locks
- Lock ordering Correct answer
Explanation: Lock ordering breaks circular wait.
2 Match deadlock concepts
| Term | Meaning |
|---|---|
Mutual exclusion |
Single owner |
Hold and wait |
Grab then wait |
Circular wait |
Cycle |
Lock ordering |
Prevention |
3 First lock
flock(____, LOCK_EX);
flock(a, LOCK_EX);
Explanation: In the ordered pattern, first a, then b is locked.