Os Deadlock Lock Ordering
DodaTech
1 min read
In this tutorial, you'll learn about How to Fix Lock Ordering Errors. We cover key concepts, practical examples, and best practices.
Fix lock ordering errors when inconsistent lock acquisition order across threads.
Quick Fix
Wrong
import threading
class Transfer:
def __init__(self):
self.lock=threading.Lock()
def transfer(self,other,amt):
self.lock.acquire()
other.lock.acquire() # inconsistent order!
self.balance-=amt; other.balance+=amt
other.lock.release(); self.lock.release()
transfer(a,b) acquires a then b. transfer(b,a) acquires b then a. Circular wait -> deadlock.
Right
import threading
class Transfer:
def __init__(self,id): self.id=id; self.lock=threading.Lock()
def transfer(self,other,amt):
# Always lock lower ID first
first, second = (self, other) if id(self) < id(other) else (other, self)
first.lock.acquire(); second.lock.acquire()
self.balance-=amt; other.balance+=amt
second.lock.release(); first.lock.release()
# Or use resource hierarchy:
lock1=threading.Lock(); lock2=threading.Lock()
def worker():
with lock1: # both threads acquire in same order
with lock2: pass
Lock ordering prevents deadlock. Both transfers acquire locks in consistent order.
Prevention
Always acquire locks in global consistent order. Use resource hierarchy numbering.
DodaTech Tools
Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro