What is Deadlock in OS: Explanation, Example, and Use Cases
deadlock in an operating system is a situation where two or more processes are stuck waiting for each other to release resources, so none can proceed. It happens when each process holds a resource and waits for another resource held by another process, creating a cycle of waiting.How It Works
Imagine two people each holding a key to a different door, and each needs the other's key to open their own door. Neither can move forward because they are waiting for the other to give up their key. This is similar to a deadlock in an operating system.
In OS terms, processes need resources like files, printers, or memory. If Process A holds Resource 1 and waits for Resource 2, while Process B holds Resource 2 and waits for Resource 1, both get stuck forever. This cycle of waiting with no one releasing resources causes the system to freeze those processes.
Deadlocks happen when four conditions occur together: mutual exclusion (only one process can use a resource at a time), hold and wait (processes hold resources while waiting for others), no preemption (resources cannot be forcibly taken), and circular wait (a cycle of processes each waiting for a resource held by the next).
Example
import threading import time lock1 = threading.Lock() lock2 = threading.Lock() def thread1(): with lock1: print('Thread 1 acquired lock1') time.sleep(1) print('Thread 1 waiting for lock2') with lock2: print('Thread 1 acquired lock2') def thread2(): with lock2: print('Thread 2 acquired lock2') time.sleep(1) print('Thread 2 waiting for lock1') with lock1: print('Thread 2 acquired lock1') # Start threads t1 = threading.Thread(target=thread1) t2 = threading.Thread(target=thread2) t1.start() t2.start() t1.join() t2.join()
When to Use
Deadlock is not something to 'use' but rather a problem to avoid or handle in operating systems and concurrent programming. Understanding deadlocks helps developers design systems that prevent or recover from them.
Deadlocks commonly occur in databases when transactions lock rows and wait for others, in multitasking OS when processes compete for hardware resources, and in multithreaded programs accessing shared data.
System designers use techniques like resource ordering, timeout, deadlock detection algorithms, or resource preemption to manage deadlocks and keep systems running smoothly.
Key Points
- Deadlock happens when processes wait forever for resources held by each other.
- It requires four conditions: mutual exclusion, hold and wait, no preemption, and circular wait.
- Deadlocks cause system freezes or slowdowns if not handled.
- Detecting and preventing deadlocks is important in OS and concurrent programming.