What is a deadlock, and what are the four Coffman conditions that must hold for one to occur?
A deadlock occurs when two or more threads are blocked forever, each one waiting for a resource that is held by another thread in the same cycle, so none of them can ever make progress. Coffman's four conditions describe the necessary and jointly sufficient requirements for a deadlock, meaning all four must be true simultaneously for one to happen. Mutual exclusion means a resource can only be held by one thread at a time. Hold and wait means a thread is holding at least one resource while it waits to acquire another. No preemption means a resource cannot be forcibly taken away from the thread holding it. Circular wait means there is a cycle of threads, each waiting for a resource held by the next thread in the cycle. Preventing deadlock just requires breaking any single one of these four conditions, and the easiest one to break in practice is circular wait, typically by enforcing a consistent global ordering on lock acquisition, such as always locking objects in order of their ID, lowest first.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response