You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
1.0 KiB
36 lines
1.0 KiB
import threading
|
|
|
|
class ReadWriteLock:
|
|
def __init__(self):
|
|
self._rw_lock = threading.Lock()
|
|
self._readers = 0
|
|
self._writers_waiting = 0
|
|
self._writer = False
|
|
self._cond = threading.Condition(self._rw_lock)
|
|
|
|
def acquire_read(self):
|
|
with self._cond:
|
|
# 如果已有写锁,或有写者在等待,都要等
|
|
while self._writer or self._writers_waiting > 0:
|
|
self._cond.wait()
|
|
self._readers += 1
|
|
|
|
def release_read(self):
|
|
with self._cond:
|
|
self._readers -= 1
|
|
if self._readers == 0:
|
|
self._cond.notify_all()
|
|
|
|
def acquire_write(self):
|
|
with self._cond:
|
|
self._writers_waiting += 1
|
|
# 等到没人读、没人写
|
|
while self._writer or self._readers > 0:
|
|
self._cond.wait()
|
|
self._writers_waiting -= 1
|
|
self._writer = True
|
|
|
|
def release_write(self):
|
|
with self._cond:
|
|
self._writer = False
|
|
self._cond.notify_all()
|