MCPcopy Create free account
hub / github.com/dabeaz/python-cookbook / acquire

Function acquire

src/12/locking_with_deadlock_avoidance/deadlock.py:8–28  ·  view source on GitHub ↗
(*locks)

Source from the content-addressed store, hash-verified

6
7@contextmanager
8def acquire(*locks):
9 # Sort locks by object identifier
10 locks = sorted(locks, key=lambda x: id(x))
11
12 # Make sure lock order of previously acquired locks is not violated
13 acquired = getattr(_local, 'acquired',[])
14 if acquired and max(id(lock) for lock in acquired) >= id(locks[0]):
15 raise RuntimeError('Lock Order Violation')
16
17 # Acquire all of the locks
18 acquired.extend(locks)
19 _local.acquired = acquired
20 try:
21 for lock in locks:
22 lock.acquire()
23 yield
24 finally:
25 # Release locks in reverse order of acquisition
26 for lock in reversed(locks):
27 lock.release()
28 del acquired[-len(locks):]

Callers 5

philosopherFunction · 0.90
thread_1Function · 0.90
thread_2Function · 0.90
thread_1Function · 0.90
thread_2Function · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected