Junior — Middle
What methods exist for preventing and resolving deadlocks in a system?
sobes.tech AI
Answer from AI
A deadlock occurs when two or more threads are permanently blocked, waiting for resources to be released. The following methods are used to prevent and eliminate deadlocks:
-
Avoiding deadlocks:
- Using a fixed order of lock acquisition (lock ordering).
- Applying timeouts when attempting to acquire locks.
- Using non-blocking algorithms and data structures.
-
Detecting deadlocks:
- Monitoring the state of threads and resources.
- Analyzing the wait-for graph to identify cycles.
-
Resolving deadlocks:
- Forcibly interrupting or rolling back one of the threads.
- Releasing resources and retrying lock acquisition.
In Python, to prevent deadlocks, you can use the threading module with timeouts:
import threading
lock1 = threading.Lock()
lock2 = threading.Lock()
def thread1():
with lock1:
if lock2.acquire(timeout=1):
try:
# critical section
pass
finally:
lock2.release()
def thread2():
with lock2:
if lock1.acquire(timeout=1):
try:
# critical section
pass
finally:
lock1.release()
Thus, using timeouts and proper lock acquisition order helps avoid deadlocks.