Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 45 additions & 36 deletions casbin/util/rwlock.py
Original file line number Diff line number Diff line change
@@ -1,56 +1,65 @@
# Copyright 2021 The casbin Authors. All Rights Reserved.
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

"""Compatibility wrappers for the separately installed MIT-licensed readerwriterlock.

A lock handle from that library records acquisition state. Give each acquisition
its own handle so the context objects shared by SyncedEnforcer remain safe when
several threads enter the same read context concurrently.
"""

from threading import RLock, Condition
from threading import local

# This implementation was adapted from https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock
from readerwriterlock.rwlock import RWLockWrite as _WriterPreferredLock


class _ThreadLocks(local):
def __init__(self):
self.read = []
self.write = []


class RWLockWrite:
"""write preferring readers-wirter lock"""
"""A writer-preferring lock retaining Casbin's existing context/direct API."""

def __init__(self):
self._lock = RLock()
self._cond = Condition(self._lock)
self._active_readers = 0
self._waiting_writers = 0
self._writer_active = False
self._delegate = _WriterPreferredLock()
self._held = _ThreadLocks()

def aquire_read(self):
with self._lock:
while self._waiting_writers > 0 or self._writer_active:
self._cond.wait()
self._active_readers += 1
# Preserve the historical method spelling for existing callers.
handle = self._delegate.gen_rlock()
handle.acquire()
self._held.read.append(handle)

def release_read(self):
with self._lock:
self._active_readers -= 1
if self._active_readers == 0:
self._cond.notify_all()
if not self._held.read:
raise RuntimeError("No read lock acquired by this thread")
self._held.read.pop().release()

def aquire_write(self):
with self._lock:
self._waiting_writers += 1
while self._active_readers > 0 or self._writer_active:
self._cond.wait()
self._waiting_writers -= 1
self._writer_active = True
handle = self._delegate.gen_wlock()
handle.acquire()
self._held.write.append(handle)

def release_write(self):
with self._lock:
self._writer_active = False
self._cond.notify_all()
if not self._held.write:
raise RuntimeError("No write lock acquired by this thread")
self._held.write.pop().release()

def gen_rlock(self):
return ReadRWLock(self)
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
simpleeval >= 1.0.3
wcmatch >= 10.1
wcmatch >= 10.1
readerwriterlock >= 1.0.9, < 2
54 changes: 54 additions & 0 deletions tests/util/test_rwlock.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,63 @@
from concurrent.futures import ThreadPoolExecutor
import time
import queue
import threading


class TestRWLock(TestCase):
def test_shared_read_context_keeps_both_readers_locked(self):
lock = RWLockWrite()
read = lock.gen_rlock()
entered = [threading.Event(), threading.Event()]
leave = [threading.Event(), threading.Event()]
finished = [threading.Event(), threading.Event()]
written = threading.Event()

def reader(index):
with read:
entered[index].set()
leave[index].wait(5)
finished[index].set()

def writer():
with lock.gen_wlock():
written.set()

threads = [threading.Thread(target=reader, args=(i,), daemon=True) for i in range(2)]
for thread in threads:
thread.start()
writer_thread = threading.Thread(target=writer, daemon=True)
try:
self.assertTrue(all(event.wait(2) for event in entered))
writer_thread.start()
self.assertFalse(written.wait(0.05))
leave[0].set()
self.assertTrue(finished[0].wait(2))
self.assertFalse(written.wait(0.05))
leave[1].set()
self.assertTrue(written.wait(2))
finally:
for event in leave:
event.set()
for thread in threads:
thread.join(2)
if writer_thread.ident is not None:
writer_thread.join(2)

def test_direct_api_and_nested_read_contexts(self):
lock = RWLockWrite()
lock.aquire_read()
with lock.gen_rlock():
pass
lock.release_read()
lock.aquire_write()
lock.release_write()
with self.assertRaises(ValueError):
with lock.gen_wlock():
raise ValueError("caller failure")
with lock.gen_wlock():
pass

def gen_locks(self):
rw_lock = RWLockWrite()
rl = rw_lock.gen_rlock()
Expand Down
Loading