Middle — Middle+
How is a deadlock situation prevented in multithreaded systems?
sobes.tech AI
Answer from AI
Deadlock occurs when multiple threads wait for resources held by each other, and none can proceed. The following approaches are used to prevent deadlock:
-
Avoid cyclic dependencies: ensure that threads acquire resources in the same order.
-
Use timeouts: when attempting to acquire a lock with a timeout, a thread can give up and release already acquired resources.
-
Avoid nested locking: minimize the number of resources acquired simultaneously.
-
Detection and recovery algorithms: periodically check for deadlocks and interrupt or restart threads.
An example in Python using ordered lock acquisition:
import threading
lock_a = threading.Lock()
lock_b = threading.Lock()
# Thread 1
with lock_a:
with lock_b:
# critical section
pass
# Thread 2
with lock_a: # acquire lock_a before lock_b to prevent deadlock
with lock_b:
# critical section
pass
Here, both threads acquire locks in the same order, preventing deadlock.