Junior — Middle
Can you explain what is meant by a deadlock in a system?
sobes.tech AI
Answer from AI
Deadlock is a situation in a multithreaded or multiprocess system where two or more processes (or threads) wait for resources held by each other, and none of them can continue working.
Example: Process A has acquired resource 1 and is waiting for resource 2, while process B has acquired resource 2 and is waiting for resource 1. Both processes are blocked forever.
In Python programming, deadlock can occur when using threads and locks. To avoid deadlock, you should:
- Try to acquire locks in the same order.
- Use timeouts when waiting for locks.
- Minimize the number of resources acquired simultaneously.
import threading
lock1 = threading.Lock()
lock2 = threading.Lock()
# Possible deadlock
def thread1():
with lock1:
with lock2:
print("Thread 1 acquired both locks")
def thread2():
with lock2:
with lock1:
print("Thread 2 acquired both locks")
Here, both threads can get blocked if they acquire locks in different orders.