-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread_write_lock.py
85 lines (60 loc) · 1.98 KB
/
read_write_lock.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from threading import Condition, RLock
class RWLock:
def __init__(self, read_write_lock):
self.rwl = read_write_lock
def __enter__(self):
self.acquire()
def __exit__(self, exc_type, exc_val, exc_tb):
self.release()
def acquire(self):
pass
def release(self):
pass
class ReadRWLock(RWLock):
def acquire(self):
self.rwl.reader_condition.acquire()
try:
while self.rwl.writers:
self.rwl.reader_condition.wait()
self.rwl.readers += 1
finally:
self.rwl.reader_condition.release()
def release(self):
self.rwl.reader_condition.acquire()
try:
self.rwl.readers -= 1
if self.rwl.writers and not self.rwl.readers:
self.rwl.writer_condition.notify_all()
finally:
self.rwl.reader_condition.release()
class WriteRWLock(RWLock):
def acquire(self):
self.rwl.writer_condition.acquire()
self.rwl.writers += 1
while self.rwl.readers:
self.rwl.writer_condition.wait()
def release(self):
self.rwl.writers -= 1
if self.rwl.readers and not self.rwl.writers:
self.rwl.reader_condition.acquire()
self.rwl.writer_condition.release()
class ReadWriteLockMeta:
def __init__(self):
lock = RLock()
self.reader_condition = Condition(lock)
self.writer_condition = Condition(lock)
self.readers = 0
self.writers = 0
def get_RWLocks():
rwlock_meta = ReadWriteLockMeta()
return ReadRWLock(rwlock_meta), WriteRWLock(rwlock_meta)
def read_lock(method):
def wrapper(self, *args, **kwargs):
with self.read_lock:
return method(self, *args, **kwargs)
return wrapper
def write_lock(method):
def wrapper(self, *args, **kwargs):
with self.write_lock:
return method(self, *args, **kwargs)
return wrapper