Interview question
What is a deadlock and how can it happen with threads? Deadlock क्या है और threads के साथ यह कैसे हो सकता है?
Answer
A deadlock occurs when two or more threads are each waiting for a resource held by the other, so none can proceed - the program freezes indefinitely.
import threading
import time
lock_a = threading.Lock()
lock_b = threading.Lock()
def task1():
with lock_a:
print('Task1 acquired lock_a')
time.sleep(0.1) # gives task2 time to acquire lock_b
print('Task1 waiting for lock_b')
with lock_b: # blocks here if task2 already holds lock_b
print('Task1 acquired lock_b')
def task2():
with lock_b:
print('Task2 acquired lock_b')
time.sleep(0.1)
print('Task2 waiting for lock_a')
with lock_a: # blocks here - DEADLOCK: each waits on what the other holds
print('Task2 acquired lock_a')
# t1 = threading.Thread(target=task1)
# t2 = threading.Thread(target=task2)
# t1.start(); t2.start()
# Program hangs forever - classic deadlock
# FIX 1: always acquire locks in the SAME consistent order across all threads
def task1_fixed():
with lock_a:
with lock_b:
print('Task1 done')
def task2_fixed():
with lock_a: # same order as task1_fixed - lock_a first, then lock_b
with lock_b:
print('Task2 done')
# FIX 2: use a timeout when acquiring locks to avoid indefinite blocking
acquired = lock_a.acquire(timeout=2)
if acquired:
try:
pass # do work
finally:
lock_a.release()
else:
print('Could not acquire lock in time, avoiding deadlock')Deadlock तब होता है जब दो या ज़्यादा threads एक-दूसरे के पास मौजूद resource का इंतज़ार करते हैं, कोई आगे नहीं बढ़ पाता - program हमेशा के लिए freeze हो जाता है।
import threading
import time
lock_a = threading.Lock()
lock_b = threading.Lock()
def task1():
with lock_a:
print('Task1 ने lock_a लिया')
time.sleep(0.1)
with lock_b: # यहां block होता है अगर task2 lock_b रखता है
print('Task1 ने lock_b लिया')
def task2():
with lock_b:
print('Task2 ने lock_b लिया')
time.sleep(0.1)
with lock_a: # DEADLOCK
print('Task2 ने lock_a लिया')
# Program हमेशा के लिए hang हो जाता है
# FIX 1: सभी threads में locks एक ही consistent order में acquire करें
def task1_fixed():
with lock_a:
with lock_b:
print('Task1 पूरा')
def task2_fixed():
with lock_a: # same order
with lock_b:
print('Task2 पूरा')
# FIX 2: timeout use करें
acquired = lock_a.acquire(timeout=2)
if acquired:
try:
pass
finally:
lock_a.release()
else:
print('Lock time पर नहीं मिला, deadlock से बचा')Was this answer clear?