Junior — Middle
When have you encountered deadlock situations, and how did you resolve them?
sobes.tech AI
Answer from AI
Mutual deadlock (deadlock) in Python can occur when threads or processes wait for each other to release resources.
For example, two threads might try to acquire two lock objects (Lock) in different orders, leading to a deadlock.
To resolve such situations:
- Avoid nested locks or always acquire locks in the same order.
- Use timeouts when acquiring locks to prevent infinite waiting.
- Use higher-level synchronization primitives like
RLockorSemaphore.
Example:
import threading
lock1 = threading.Lock()
lock2 = threading.Lock()
def thread1():
with lock1:
print("Thread 1 acquired lock1")
with lock2:
print("Thread 1 acquired lock2")
def thread2():
with lock2:
print("Thread 2 acquired lock2")
with lock1:
print("Thread 2 acquired lock1")
# This code can lead to deadlock if both threads run simultaneously.
To avoid deadlock, ensure that all threads acquire locks in the same order.