-
Notifications
You must be signed in to change notification settings - Fork 0
/
RWLock.py
41 lines (34 loc) · 1.17 KB
/
RWLock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Ref: Python Cookbook, ISBN: 780596001674
import threading
class ReadWriteLock:
""" A lock object that allows many simultaneous "read locks", but
only one "write lock." """
def __init__(self):
self._read_ready = threading.Condition(threading.Lock())
self._readers = 0
def acquire_read(self):
""" Acquire a read lock. Blocks only if a thread has
acquired the write lock. """
self._read_ready.acquire( )
try:
self._readers += 1
finally:
self._read_ready.release( )
def release_read(self):
""" Release a read lock. """
self._read_ready.acquire( )
try:
self._readers -= 1
if not self._readers:
self._read_ready.notifyAll( )
finally:
self._read_ready.release( )
def acquire_write(self):
""" Acquire a write lock. Blocks until there are no
acquired read or write locks. """
self._read_ready.acquire( )
while self._readers > 0:
self._read_ready.wait( )
def release_write(self):
""" Release a write lock. """
self._read_ready.release( )