Listen to this Post
A deadlock occurs when two or more transactions are waiting for each other to release locks on resources. This creates a situation where no transaction can proceed, leaving them in an indefinite waiting state.
Deadlock Prevention
- Resource Ordering: Each process requests resources in a strictly increasing order to prevent circular waits.
- Timeouts: A process that holds resources for too long can be rolled back automatically.
- Banker’s Algorithm: A deadlock avoidance algorithm that checks if granting a resource request leads to a safe state.
Deadlock Recovery
1. Select a Transaction for Rollback:
- Modern DBMS and OS detect deadlocks using algorithms (e.g., wait-for graphs).
- Criteria include transaction priority, resource utilization, and rollback cost.
2. Rollback:
- The system rolls back part or all of a transaction to break the deadlock.
- Rolled-back transactions may restart automatically.
You Should Know:
Linux Commands for Deadlock Detection & Handling
[sh]
Check running processes and resource usage
top
htop
List open files and locks (Linux)
lsof
fuser -v /path/to/resource
Kill a process forcefully
kill -9
Check for deadlocks in MySQL
SHOW ENGINE INNODB STATUS;
PostgreSQL deadlock log
grep “deadlock” /var/log/postgresql/postgresql-*.log
[/sh]
#### **Windows Commands for Deadlock Analysis**
<h1>List processes and resource handles</h1> handle.exe tasklist <h1>Check SQL Server deadlocks</h1> SELECT * FROM sys.dm_tran_locks;
#### **Database Deadlock Simulation (SQL Example)**
-- Transaction 1 BEGIN TRANSACTION; UPDATE Accounts SET balance = balance - 100 WHERE id = 1; -- Wait UPDATE Accounts SET balance = balance + 100 WHERE id = 2; COMMIT; -- Transaction 2 (Run in parallel) BEGIN TRANSACTION; UPDATE Accounts SET balance = balance - 50 WHERE id = 2; -- Deadlock occurs UPDATE Accounts SET balance = balance + 50 WHERE id = 1; COMMIT;
#### **Preventing Deadlocks in Code (Python Example)**
import threading from contextlib import contextmanager <h1>Resource ordering to prevent deadlocks</h1> lock1 = threading.Lock() lock2 = threading.Lock() @contextmanager def acquire_locks_in_order(): lock1.acquire() lock2.acquire() try: yield finally: lock2.release() lock1.release()
### **What Undercode Say**
Deadlocks are a critical issue in concurrent systems. Prevention is better than recovery—use resource ordering, timeouts, and deadlock detection mechanisms. In databases, monitor locks and optimize transactions. In OS-level debugging, tools like strace, lsof, and `gdb` help trace stuck processes. Always implement proper logging to diagnose deadlocks quickly.
### **Expected Output:**
- Deadlock detection logs in databases.
- System process termination or rollback.
- Successful transaction retries after deadlock resolution.
Reference: System Design Interview – Deadlocks
References:
Reported By: Sahnlam What – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅



