The thumbnail is what GPT produced when I asked it to draw philosophers dining with forks (the forks ended up in the middle of the table, haha). The dining philosophers problem is a famous synchronization problem. In this post, we will explore synchronization problems through examples.
Technical interviews often ask
which tool to use in which situation
, rather than simply testing definitions. Practical examples help you become familiar with these scenarios.
A producer adds data to a shared buffer, while a consumer removes it. Each must wait appropriately when the buffer is full or empty.
Solution: use two semaphores and a mutex to coordinate the producer and consumer.
Five philosophers sit around a circular table, with one fork between each pair. Each philosopher must acquire both the left and right forks before eating. This creates a synchronization problem.
Problem: if all philosophers pick up one fork at the same time and wait, a deadlock can occur.
Solution: use strategies such as varying the fork acquisition order for odd- and even-numbered philosophers, or limiting the number of participating philosophers.
Synchronization is essential inside the operating system too, because multiple processes can access the kernel concurrently through system calls.
For example, when multiple processes try to modify the same file, a file system uses a
lock
to coordinate their order.
Solutions include spinlocks and reader-writer locks.
A reader-writer lock controls reads and writes separately.
Multiple readers can access data simultaneously, allowing parallel reads.
A writer has exclusive access, blocking both reads and writes.
Improves performance when reads are frequent and writes are rare.
Maximizes concurrency while preserving data consistency.
Read lock: multiple threads can acquire it simultaneously.
Write lock: only one thread can acquire it exclusively.
Reader-priority or writer-priority policies can be chosen.
What is POSIX?
POSIX stands for Portable Operating System Interface, a project providing standardized operating system interfaces. POSIX standards are designed to ensure consistent behavior across operating systems. Most operating systems we use, such as Linux, macOS, and Windows, follow POSIX standards.
In a POSIX environment, the pthread library provides access to mutexes and semaphores.