pax_global_header00006660000000000000000000000064137445077260014531gustar00rootroot0000000000000052 comment=09ef943442e0fd05d4bef98136e010d874cad3ef aiorwlock-1.0.0/000077500000000000000000000000001374450772600135215ustar00rootroot00000000000000aiorwlock-1.0.0/.coveragerc000066400000000000000000000001021374450772600156330ustar00rootroot00000000000000[run] branch = True source = aiorwlock omit = site-packages, .tox aiorwlock-1.0.0/.github/000077500000000000000000000000001374450772600150615ustar00rootroot00000000000000aiorwlock-1.0.0/.github/workflows/000077500000000000000000000000001374450772600171165ustar00rootroot00000000000000aiorwlock-1.0.0/.github/workflows/ci.yml000066400000000000000000000057711374450772600202460ustar00rootroot00000000000000name: CI on: push: branches: - master tags: [ 'v*' ] pull_request: branches: - master schedule: - cron: '0 6 * * *' # Daily 6AM UTC build jobs: lint: name: Linter runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Checkout uses: actions/checkout@v2 - name: Setup Python 3.8 uses: actions/setup-python@v2 with: python-version: 3.8 - name: Get pip cache dir id: pip-cache run: | echo "::set-output name=dir::$(pip cache dir)" # - name: Cache - name: Cache PyPI uses: actions/cache@v2 with: key: pip-lint-${{ hashFiles('requirements-dev.txt') }} path: ${{ steps.pip-cache.outputs.dir }} restore-keys: | pip-lint- - name: Install dependencies uses: py-actions/py-dependency-install@v2 with: path: requirements-dev.txt - name: Install itself run: | pip install . - name: Run lint run: | make lint - name: Prepare twine checker run: | pip install -U twine wheel python setup.py sdist bdist_wheel - name: Run twine checker run: | twine check dist/* test: name: Test needs: lint strategy: matrix: pyver: [3.6, 3.7, 3.8, 3.9, pypy3] fail-fast: false runs-on: ubuntu-latest timeout-minutes: 15 steps: - name: Checkout uses: actions/checkout@v2 - name: Setup Python ${{ matrix.pyver }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.pyver }} - name: Get pip cache dir id: pip-cache run: | echo "::set-output name=dir::$(pip cache dir)" # - name: Cache - name: Cache PyPI uses: actions/cache@v2 with: key: pip-ci-${{ matrix.pyver }}-${{ hashFiles('requirements-dev.txt') }} path: ${{ steps.pip-cache.outputs.dir }} restore-keys: | pip-ci- - name: Install dependencies uses: py-actions/py-dependency-install@v2 with: path: requirements-dev.txt - name: Run unittests env: COLOR: 'yes' run: | make cov python -m coverage xml - name: Upload coverage uses: codecov/codecov-action@v1 with: file: ./coverage.xml flags: unit fail_ci_if_error: false deploy: name: Deploy runs-on: ubuntu-latest needs: test # Run only on pushing a tag if: github.event_name == 'push' && contains(github.ref, 'refs/tags/') steps: - name: Checkout uses: actions/checkout@v2 - name: Setup Python 3.8 uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install dependencies run: python -m pip install -U pip wheel twine - name: Make dists run: python setup.py sdist bdist_wheel - name: PyPI upload env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} run: | twine upload dist/* aiorwlock-1.0.0/.gitignore000066400000000000000000000014061374450772600155120ustar00rootroot00000000000000># Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .cache nosetests.xml coverage.xml cover # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ # PyCharm .idea .coverage.* coverage .DS_Store .mypy_cache/ cscope.files cscope.out tags aiorwlock-1.0.0/.pyup.yml000066400000000000000000000001231374450772600153130ustar00rootroot00000000000000# Label PRs with `deps-update` label label_prs: deps-update schedule: every month aiorwlock-1.0.0/CHANGES.rst000066400000000000000000000023071374450772600153250ustar00rootroot00000000000000Changes ------- 1.0.0 (2020-12-32) ^^^^^^^^^^^^^^^^^^ * Fix a bug with cancelation during acquire #170 (thanks @romasku) * Deprecate passing explicit `loop` argument to `RWLock` constuctor * Deprecate creation of `RWLock` instance outside of async function context * Minimal supported version is Python 3.6 * The library works with Python 3.8 and Python 3.9 seamlessly 0.6.0 (2018-12-18) ^^^^^^^^^^^^^^^^^^ * Wake up all readers after writer releases lock #60 (thanks @ranyixu) * Fixed Python 3.7 compatibility * Removed old `yield from` syntax * Minimal supported version is Python 3.5.3 * Removed support for none async context managers 0.5.0 (2017-12-03) ^^^^^^^^^^^^^^^^^^ * Fix corner cases and deadlock when we upgrade lock from write to read #39 * Use loop.create_future instead asyncio.Future if possible 0.4.0 (2015-09-20) ^^^^^^^^^^^^^^^^^^ * Support Python 3.5 and `async with` statement * rename `.reader_lock` -> `.reader`, `.writer_lock` -> `.writer`. Backward compatibility is preserved. 0.3.0 (2014-02-11) ^^^^^^^^^^^^^^^^^^ * Add `.locked` property 0.2.0 (2014-02-09) ^^^^^^^^^^^^^^^^^^ * Make `.release()` non-coroutine 0.1.0 (2014-12-22) ^^^^^^^^^^^^^^^^^^ * Initial release aiorwlock-1.0.0/LICENSE000066400000000000000000000261041374450772600145310ustar00rootroot00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2015-2019 Andrew Svetlov, Nikolay Novik 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 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. aiorwlock-1.0.0/MANIFEST.in000066400000000000000000000002131374450772600152530ustar00rootroot00000000000000include LICENSE include CHANGES.rst include README.rst include Makefile graft aiorwlock graft tests global-exclude *.pyc prune docs/_build aiorwlock-1.0.0/Makefile000066400000000000000000000021671374450772600151670ustar00rootroot00000000000000# Some simple testing tasks (sorry, UNIX only). FILES := aiorwlock tests examples setup.py flake: flake8 $(FILES) fmt: isort ${FILES} black -S -l 79 ${FILES} lint: bandit pyroma isort --check-only --diff ${FILES} black -S -l 79 --check $(FILES) mypy --show-error-codes --disallow-untyped-calls --strict aiorwlock flake8 $(FILES) test: flake pytest -s vtest: pytest -v pyroma: pyroma -d . bandit: bandit -r ./aiorwlock mypy: mypy aiorwlock --disallow-untyped-calls --strict cov cover coverage: pytest -sv --cov=aiorwlock --cov-report=term --cov-report=html ./tests @echo "open file://`pwd`/htmlcov/index.html" clean: rm -rf `find . -name __pycache__` rm -f `find . -type f -name '*.py[co]' ` rm -f `find . -type f -name '*~' ` rm -f `find . -type f -name '.*~' ` rm -f `find . -type f -name '@*' ` rm -f `find . -type f -name '#*#' ` rm -f `find . -type f -name '*.orig' ` rm -f `find . -type f -name '*.rej' ` rm -f .coverage rm -rf coverage rm -rf build rm -rf cover rm -rf dist doc: make -C docs html @echo "open file://`pwd`/docs/_build/html/index.html" .PHONY: all flake test vtest cov clean doc aiorwlock-1.0.0/README.rst000066400000000000000000000051641374450772600152160ustar00rootroot00000000000000aiorwlock ========= .. image:: https://github.com/aio-libs/aiorwlock/workflows/CI/badge.svg :target: https://github.com/aio-libs/aiorwlock/actions?query=workflow%3ACI .. image:: https://codecov.io/gh/aio-libs/aiorwlock/branch/master/graph/badge.svg :target: https://codecov.io/gh/aio-libs/aiorwlock .. image:: https://badges.gitter.im/Join%20Chat.svg :target: https://gitter.im/aio-libs/Lobby :alt: Chat on Gitter Read write lock for asyncio_ . A ``RWLock`` maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader tasks, so long as there are no writers. The write lock is exclusive. Whether or not a read-write lock will improve performance over the use of a mutual exclusion lock depends on the frequency that the data is *read* compared to being *modified*. For example, a collection that is initially populated with data and thereafter infrequently modified, while being frequently searched is an ideal candidate for the use of a read-write lock. However, if updates become frequent then the data spends most of its time being exclusively locked and there is little, if any increase in concurrency. Implementation is almost direct port from this patch_. Example ------- Requires Python 3.5.3+ .. code:: python import asyncio import aiorwlock async def go(): rwlock = aiorwlock.RWLock() # acquire reader lock, multiple coroutines allowed to hold the lock async with rwlock.reader_lock: print('inside reader lock') await asyncio.sleep(0.1) # acquire writer lock, only one coroutine can hold the lock async with rwlock.writer_lock: print('inside writer lock') await asyncio.sleep(0.1) loop = asyncio.get_event_loop() loop.run_until_complete(go()) Fast path --------- By default `RWLock` switches context on lock acquiring. That allows to other waiting tasks get the lock even if task that holds the lock doesn't contain context switches (`await fut` statements). The default behavior can be switched off by `fast` argument: `RWLock(fast=True)`. Long story short: lock is safe by default, but if you sure you have context switches (`await`, `async with`, `async for` or `yield from` statements) inside locked code you may want to use `fast=True` for minor speedup. TLA+ Specification ------------------ TLA+ specification of ``aiorwlock`` provided in this repository. License ------- ``aiorwlock`` is offered under the Apache 2 license. .. _asyncio: http://docs.python.org/3.8/library/asyncio.html .. _patch: http://bugs.python.org/issue8800 aiorwlock-1.0.0/aiorwlock/000077500000000000000000000000001374450772600155135ustar00rootroot00000000000000aiorwlock-1.0.0/aiorwlock/__init__.py000066400000000000000000000214401374450772600176250ustar00rootroot00000000000000import asyncio import warnings from collections import deque from typing import Any, Deque, List, Optional, Tuple Loop = asyncio.AbstractEventLoop OptLoop = Optional[Loop] # silence LGTM service alerts Future = asyncio.Future Task = asyncio.Task __version__ = '1.0.0' __all__ = ('RWLock',) def _current_task(loop: OptLoop = None) -> 'Task[Any]': _loop: Loop = loop or asyncio.get_event_loop() if hasattr(asyncio, 'current_task'): t = asyncio.current_task(loop=_loop) else: # remove once python 3.6 deprecated t = asyncio.Task.current_task(loop=_loop) if t is None: raise RuntimeError('Loop is not running') return t # implementation based on: # http://bugs.python.org/issue8800 # The internal lock object managing the RWLock state. class _RWLockCore: _RL = 1 _WL = 2 def __init__(self, fast: bool, loop: Loop): self._do_yield = not fast self._loop: Loop = loop self._read_waiters: Deque[Future[None]] = deque() self._write_waiters: Deque[Future[None]] = deque() self._r_state: int = 0 self._w_state: int = 0 # tasks will be few, so a list is not inefficient self._owning: List[Tuple[Task[Any], int]] = [] @property def read_locked(self) -> bool: return self._r_state > 0 @property def write_locked(self) -> bool: return self._w_state > 0 async def _yield_after_acquire(self, lock_type: int) -> None: if self._do_yield: try: await asyncio.sleep(0.0, loop=self._loop) except asyncio.CancelledError: self._release(lock_type) self._wake_up() raise # Acquire the lock in read mode. async def acquire_read(self) -> bool: me = _current_task(loop=self._loop) if (me, self._RL) in self._owning or (me, self._WL) in self._owning: self._r_state += 1 self._owning.append((me, self._RL)) await self._yield_after_acquire(self._RL) return True if ( not self._write_waiters and self._r_state >= 0 and self._w_state == 0 ): self._r_state += 1 self._owning.append((me, self._RL)) await self._yield_after_acquire(self._RL) return True fut = self._loop.create_future() self._read_waiters.append(fut) try: await fut self._r_state += 1 self._owning.append((me, self._RL)) return True except asyncio.CancelledError: self._wake_up() raise finally: self._read_waiters.remove(fut) # Acquire the lock in write mode. A 'waiting' count is maintained, # ensuring that 'readers' will yield to writers. async def acquire_write(self) -> bool: me = _current_task(loop=self._loop) if (me, self._WL) in self._owning: self._w_state += 1 self._owning.append((me, self._WL)) await self._yield_after_acquire(self._WL) return True elif (me, self._RL) in self._owning: if self._r_state > 0: raise RuntimeError('Cannot upgrade RWLock from read to write') if self._r_state == 0 and self._w_state == 0: self._w_state += 1 self._owning.append((me, self._WL)) await self._yield_after_acquire(self._WL) return True fut = self._loop.create_future() self._write_waiters.append(fut) try: await fut self._w_state += 1 self._owning.append((me, self._WL)) return True except asyncio.CancelledError: self._wake_up() raise finally: self._write_waiters.remove(fut) def release_read(self) -> None: self._release(self._RL) def release_write(self) -> None: self._release(self._WL) def _release(self, lock_type: int) -> None: # assert lock_type in (self._RL, self._WL) me = _current_task(loop=self._loop) try: self._owning.remove((me, lock_type)) except ValueError: raise RuntimeError('Cannot release an un-acquired lock') if lock_type == self._RL: self._r_state -= 1 else: self._w_state -= 1 self._wake_up() def _wake_up(self) -> None: # If no one is reading or writing, wake up write waiters # first, only one write waiter should be waken up, if no # write waiters and have read waiters, wake up all read # waiters. if self._r_state == 0 and self._w_state == 0: if self._write_waiters: self._wake_up_first(self._write_waiters) elif self._read_waiters: self._wake_up_all(self._read_waiters) def _wake_up_first(self, waiters: 'Deque[Future[None]]') -> None: # Wake up the first waiter who isn't cancelled. for fut in waiters: if not fut.done(): fut.set_result(None) break def _wake_up_all(self, waiters: 'Deque[Future[None]]') -> None: # Wake up all not cancelled waiters. for fut in waiters: if not fut.done(): fut.set_result(None) class _ContextManagerMixin: def __enter__(self) -> None: raise RuntimeError( '"await" should be used as context manager expression' ) def __exit__(self, *args: Any) -> None: # This must exist because __enter__ exists, even though that # always raises; that's how the with-statement works. pass # pragma: no cover async def __aenter__(self) -> None: await self.acquire() # We have no use for the "as ..." clause in the with # statement for locks. return None async def __aexit__(self, *args: List[Any]) -> None: self.release() async def acquire(self) -> None: raise NotImplementedError # pragma: no cover def release(self) -> None: raise NotImplementedError # pragma: no cover # Lock objects to access the _RWLockCore in reader or writer mode class _ReaderLock(_ContextManagerMixin): def __init__(self, lock: _RWLockCore) -> None: self._lock = lock @property def locked(self) -> bool: return self._lock.read_locked async def acquire(self) -> None: await self._lock.acquire_read() def release(self) -> None: self._lock.release_read() def __repr__(self) -> str: status = 'locked' if self._lock._r_state > 0 else 'unlocked' return ''.format(status) class _WriterLock(_ContextManagerMixin): def __init__(self, lock: _RWLockCore): self._lock = lock @property def locked(self) -> bool: return self._lock.write_locked async def acquire(self) -> None: await self._lock.acquire_write() def release(self) -> None: self._lock.release_write() def __repr__(self) -> str: status = 'locked' if self._lock._w_state > 0 else 'unlocked' return ''.format(status) class RWLock: """A RWLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader tasks, so long as there are no writers. The write lock is exclusive. """ core = _RWLockCore def __init__(self, *, fast: bool = False, loop: OptLoop = None) -> None: if loop is None: loop = asyncio.get_event_loop() else: warnings.warn( 'Passing "loop" argument ' 'is deprecated since aiorwlock 1.0 and scheduled for removal ' 'in aiorwlock 2.0', DeprecationWarning, stacklevel=2, ) if not loop.is_running(): warnings.warn( 'Instantiation of RWLock outside of async function context ' 'is deprecated since aiorwlock 1.0 and scheduled for removal ' 'in aiorwlock 2.0', DeprecationWarning, stacklevel=2, ) self._loop: Loop = loop core = self.core(fast, self._loop) self._reader_lock = _ReaderLock(core) self._writer_lock = _WriterLock(core) @property def reader(self) -> _ReaderLock: """The lock used for read, or shared, access""" return self._reader_lock reader_lock = reader @property def writer(self) -> _WriterLock: """The lock used for write, or exclusive, access""" return self._writer_lock writer_lock = writer def __repr__(self) -> str: rl = self.reader_lock.__repr__() wl = self.writer_lock.__repr__() return ''.format(rl, wl) aiorwlock-1.0.0/aiorwlock/py.typed000066400000000000000000000000161374450772600172070ustar00rootroot00000000000000# placeholder aiorwlock-1.0.0/examples/000077500000000000000000000000001374450772600153375ustar00rootroot00000000000000aiorwlock-1.0.0/examples/context_manager.py000066400000000000000000000006311374450772600210670ustar00rootroot00000000000000import asyncio import aiorwlock async def go(): rwlock = aiorwlock.RWLock() # acquire reader lock async with rwlock.reader_lock: print('inside reader lock') await asyncio.sleep(0.1) # acquire writer lock async with rwlock.writer_lock: print('inside writer lock') await asyncio.sleep(0.1) loop = asyncio.get_event_loop() loop.run_until_complete(go()) aiorwlock-1.0.0/examples/simple.py000066400000000000000000000010311374450772600171750ustar00rootroot00000000000000import asyncio import aiorwlock async def go(): rwlock = aiorwlock.RWLock() # acquire reader lock await rwlock.reader_lock.acquire() try: print('inside reader lock') await asyncio.sleep(0.1) finally: rwlock.reader_lock.release() # acquire writer lock await rwlock.writer_lock.acquire() try: print('inside writer lock') await asyncio.sleep(0.1) finally: rwlock.writer_lock.release() loop = asyncio.get_event_loop() loop.run_until_complete(go()) aiorwlock-1.0.0/requirements-dev.txt000066400000000000000000000007471374450772600175710ustar00rootroot00000000000000-e . bandit==1.6.2; implementation_name=="cpython" black==20.8b1; implementation_name=="cpython" flake8-bugbear==20.1.4; implementation_name=="cpython" flake8-quotes==3.2.0; implementation_name=="cpython" flake8==3.8.4; implementation_name=="cpython" isort==5.6.4; implementation_name=="cpython" mypy==0.790; implementation_name=="cpython" pyroma==2.6; implementation_name=="cpython" pytest-asyncio==0.14.0 pytest-cov==2.10.1 pytest==6.1.1 uvloop==0.14.0; implementation_name=="cpython" aiorwlock-1.0.0/setup.cfg000066400000000000000000000001431374450772600153400ustar00rootroot00000000000000[tool:pytest] filterwarnings=error testpaths = tests/ [mypy-pytest] ignore_missing_imports = true aiorwlock-1.0.0/setup.py000066400000000000000000000034571374450772600152440ustar00rootroot00000000000000import os import re from setuptools import setup install_requires = [] def read(f): return open(os.path.join(os.path.dirname(__file__), f)).read().strip() def read_version(): regexp = re.compile(r"^__version__\W*=\W*'([\d.abrc]+)'") init_py = os.path.join( os.path.dirname(__file__), 'aiorwlock', '__init__.py' ) with open(init_py) as f: for line in f: match = regexp.match(line) if match is not None: return match.group(1) raise RuntimeError('Cannot find version in aiorwlock/__init__.py') classifiers = [ 'License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Operating System :: OS Independent', 'Development Status :: 4 - Beta', 'Framework :: AsyncIO', ] project_urls = { 'Website': 'https://github.com/aio-libs/aiorwlock', 'Issues': 'https://github.com/aio-libs/aiorwlock/issues', } setup( name='aiorwlock', version=read_version(), description=('Read write lock for asyncio.'), long_description='\n\n'.join((read('README.rst'), read('CHANGES.rst'))), classifiers=classifiers, platforms=['POSIX'], author='Nikolay Novik', author_email='nickolainovik@gmail.com', url='https://github.com/aio-libs/aiorwlock', download_url='https://pypi.python.org/pypi/aiorwlock', license='Apache 2', packages=['aiorwlock'], install_requires=install_requires, keywords=['aiorwlock', 'lock', 'asyncio'], zip_safe=True, project_urls=project_urls, python_requires='>=3.6.0', include_package_data=True, ) aiorwlock-1.0.0/spec/000077500000000000000000000000001374450772600144535ustar00rootroot00000000000000aiorwlock-1.0.0/spec/aiorwlock.tla000066400000000000000000000047721374450772600171610ustar00rootroot00000000000000----------------------------- MODULE aiorwlock ------------------------------ EXTENDS Naturals, Sequences, Integers, FiniteSets CONSTANTS Task ASSUME /\ Task # {} VARIABLES RState, WState, Lock ----------------------------------------------------------------------------- TypeOK == /\ Lock \in [Task -> {"Read", "Write", "WriteRead", "Waiting", "Finished"}] /\ RState >= 0 /\ WState >= 0 /\ WState <= 2 LockInit == Lock = [t \in Task |-> "Waiting"] /\ RState = 0 /\ WState = 0 ----------------------------------------------------------------------------- Rlocked == RState > 0 Wlocked == WState > 0 Unlocked == RState = 0 /\ WState = 0 WOwn(t) == Lock[t] \in {"Write"} RAquire(t) == \/ /\ ~Wlocked /\ Lock' = [Lock EXCEPT ![t] = "Read"] /\ RState' = RState + 1 /\ UNCHANGED WState /\ Lock[t] \in {"Waiting"} \/ /\ WOwn(t) /\ Lock' = [Lock EXCEPT ![t] = "WriteRead"] /\ RState' = RState + 1 /\ UNCHANGED WState WAquire(t) == /\ Unlocked /\ Lock' = [Lock EXCEPT ![t] = "Write"] /\ WState' = WState + 1 /\ UNCHANGED RState /\ Lock[t] \in {"Waiting"} RRelease(t) == \/ /\ Rlocked /\ Lock[t] = "Read" /\ RState' = RState - 1 /\ Lock' = [Lock EXCEPT ![t] = "Finished"] /\ UNCHANGED WState \/ /\ Rlocked /\ Lock[t] = "WriteRead" /\ RState' = RState - 1 /\ Lock' = [Lock EXCEPT ![t] = "Write"] /\ UNCHANGED WState WRelease(t) == \/ /\ Wlocked /\ Lock[t] = "Write" /\ WState' = WState - 1 /\ Lock' = [Lock EXCEPT ![t] = "Finished"] /\ UNCHANGED RState \/ /\ Wlocked /\ Lock[t] = "WriteRead" /\ WState' = WState - 1 /\ Lock' = [Lock EXCEPT ![t] = "Read"] /\ UNCHANGED RState ----------------------------------------------------------------------------- Next == \E t \in Task: RAquire(t) \/ WAquire(t) \/ RRelease(t) \/ WRelease(t) Spec == LockInit /\ [][Next]_<> LockInv == \A t1 \in Task : \A t2 \in (Task \ {t1}): ~ (/\ Lock[t1] \in {"Write", "WriteRead"} /\ Lock[t2] \in {"Read", "Write", "WriteRead"}) ----------------------------------------------------------------------------- THEOREM Spec => [](TypeOK /\ LockInv) ============================================================================= aiorwlock-1.0.0/tests/000077500000000000000000000000001374450772600146635ustar00rootroot00000000000000aiorwlock-1.0.0/tests/conftest.py000066400000000000000000000017101374450772600170610ustar00rootroot00000000000000import asyncio import gc import pytest try: import uvloop except ImportError: uvloop = None @pytest.fixture(scope='module', params=[True, False], ids=['fast', 'slow']) def fast_track(request): return request.param @pytest.fixture( scope='session', params=[True, False], ids=['debug:true', 'debug:false'] ) def debug(request): return request.param @pytest.fixture(scope='module', params=['pyloop', 'uvloop']) def loop_type(request): return request.param @pytest.fixture def event_loop(request, loop_type, debug): # old_loop = asyncio.get_event_loop() asyncio.set_event_loop(None) if loop_type == 'uvloop' and uvloop is not None: loop = uvloop.new_event_loop() else: loop = asyncio.new_event_loop() loop.set_debug(debug) asyncio.set_event_loop(loop) yield loop loop.close() asyncio.set_event_loop(None) gc.collect() @pytest.fixture def loop(event_loop): return event_loop aiorwlock-1.0.0/tests/test_corner_cases.py000066400000000000000000000064671374450772600207570ustar00rootroot00000000000000import asyncio import contextlib import pytest from aiorwlock import RWLock, _current_task ensure_future = asyncio.ensure_future @contextlib.contextmanager def should_fail(timeout, loop): task = _current_task(loop) handle = loop.call_later(timeout, task.cancel) try: yield except asyncio.CancelledError: handle.cancel() return else: msg = 'Inner task expected to be cancelled: {}'.format(task) pytest.fail(msg) @pytest.mark.asyncio async def test_get_write_then_read(loop): rwlock = RWLock() rl = rwlock.reader wl = rwlock.writer async with wl: assert wl.locked assert not rl.locked async with rl: assert wl.locked assert rl.locked @pytest.mark.asyncio async def test_get_write_then_read_and_write_again(loop): rwlock = RWLock() rl = rwlock.reader wl = rwlock.writer f = loop.create_future() writes = [] async def get_write_lock(): await f with should_fail(0.1, loop): async with wl: assert wl.locked writes.append('should not be here') ensure_future(get_write_lock()) async with wl: assert wl.locked async with rl: f.set_result(None) await asyncio.sleep(0.12) # second task can not append to writes assert writes == [] assert rl.locked @pytest.mark.asyncio async def test_writers_deadlock(loop): rwlock = RWLock() rl = rwlock.reader wl = rwlock.writer # Scenario: # - task A (this) acquires read lock # - task B,C wait for write lock # # A releases the lock and, in the same loop interation, # task B gets cancelled (eg: by timeout); # B gets cancelled without waking up next waiter -- deadlock; # # See asyncio.Lock deadlock issue: # https://github.com/python/cpython/pull/1031 async def coro(): async with wl: assert wl.locked await asyncio.sleep(0.2, loop) async with rl: assert rl.locked task_b = ensure_future(coro()) task_c = ensure_future(coro()) await asyncio.sleep(0.1, loop) # cancel lock waiter right after release task_b.cancel() assert not rl.locked # wait task_c to complete await asyncio.sleep(0.3, loop) assert task_c.done() assert not rl.locked assert not wl.locked @pytest.mark.asyncio async def test_readers_cancel(loop): rwlock = RWLock() rl = rwlock.reader wl = rwlock.writer async def coro(lock): async with lock: assert lock.locked await asyncio.sleep(0.2, loop) async with wl: assert wl.locked task_b = ensure_future(coro(rl)) task_c = ensure_future(coro(rl)) await asyncio.sleep(0.1, loop) task_b.cancel() assert not wl.locked await task_c assert task_c.done() assert not rl.locked assert not wl.locked @pytest.mark.asyncio async def test_canceled_inside_acquire(loop): rwlock = RWLock() rl = rwlock.reader async def coro(lock): async with lock: pass task = ensure_future(coro(rl)) await asyncio.sleep(0) task.cancel() try: await task except asyncio.CancelledError: pass assert not rl.locked aiorwlock-1.0.0/tests/test_rwlock.py000066400000000000000000000322301374450772600175750ustar00rootroot00000000000000import asyncio import pytest from aiorwlock import RWLock, _current_task class Bunch(object): """A bunch of Tasks. Port python threading tests""" def __init__(self, f, n, wait_before_exit=False): """ Construct a bunch of `n` tasks running the same function `f`. If `wait_before_exit` is True, the tasks won't terminate until do_finish() is called. """ self._loop = asyncio.get_event_loop() self.f = f self.n = n self.started = [] self.finished = [] self._can_exit = not wait_before_exit self._futures = [] async def task(): tid = _current_task() self.started.append(tid) try: await f() finally: self.finished.append(tid) while not self._can_exit: await asyncio.sleep(0.01) for _ in range(n): t = asyncio.Task(task()) self._futures.append(t) async def wait_for_finished(self): await asyncio.gather(*self._futures) def do_finish(self): self._can_exit = True async def _wait(): await asyncio.sleep(0.01) def test_ctor_deprecated_implicit_not_running(loop): with pytest.warns(DeprecationWarning): RWLock() def test_ctor_deprecated_explicit_non_running(loop): with pytest.warns(DeprecationWarning): RWLock(loop=loop) @pytest.mark.asyncio async def test_ctor_loop_deprecated_arg(loop): with pytest.warns(DeprecationWarning): RWLock(loop=loop) @pytest.mark.asyncio async def test_ctor_loop_reader(loop): rwlock = RWLock().reader_lock assert rwlock._lock._loop is loop @pytest.mark.asyncio async def test_ctor_noloop_reader(loop): asyncio.set_event_loop(loop) rwlock = RWLock().reader_lock assert rwlock._lock._loop is loop @pytest.mark.asyncio async def test_ctor_loop_writer(loop): rwlock = RWLock().writer_lock assert rwlock._lock._loop is loop @pytest.mark.asyncio async def test_ctor_noloop_writer(loop): asyncio.set_event_loop(loop) rwlock = RWLock().writer_lock assert rwlock._lock._loop is loop @pytest.mark.asyncio async def test_repr(loop): rwlock = RWLock() assert 'RWLock' in rwlock.__repr__() assert 'WriterLock: [unlocked' in rwlock.__repr__() assert 'ReaderLock: [unlocked' in rwlock.__repr__() # reader lock __repr__ await rwlock.reader_lock.acquire() assert 'ReaderLock: [locked]' in rwlock.__repr__() rwlock.reader_lock.release() assert 'ReaderLock: [unlocked]' in rwlock.__repr__() # writer lock __repr__ await rwlock.writer_lock.acquire() assert 'WriterLock: [locked]' in rwlock.__repr__() rwlock.writer_lock.release() assert 'WriterLock: [unlocked]' in rwlock.__repr__() @pytest.mark.asyncio async def test_release_unlocked(loop): rwlock = RWLock() with pytest.raises(RuntimeError): rwlock.reader_lock.release() @pytest.mark.asyncio async def test_many_readers(loop, fast_track): rwlock = RWLock(fast=fast_track) N = 5 locked = [] nlocked = [] async def f(): await rwlock.reader_lock.acquire() try: locked.append(1) await _wait() nlocked.append(len(locked)) await _wait() locked.pop(-1) finally: rwlock.reader_lock.release() await Bunch(f, N).wait_for_finished() assert max(nlocked) > 1 @pytest.mark.asyncio async def test_read_upgrade_write_release(loop): rwlock = RWLock() await rwlock.writer_lock.acquire() await rwlock.reader_lock.acquire() await rwlock.reader_lock.acquire() await rwlock.reader_lock.acquire() rwlock.reader_lock.release() assert rwlock.writer_lock.locked rwlock.writer_lock.release() assert not rwlock.writer_lock.locked assert rwlock.reader.locked with pytest.raises(RuntimeError): await rwlock.writer_lock.acquire() rwlock.reader_lock.release() rwlock.reader_lock.release() @pytest.mark.asyncio async def test_reader_recursion(loop, fast_track): rwlock = RWLock(fast=fast_track) N = 5 locked = [] nlocked = [] async def f(): await rwlock.reader_lock.acquire() try: await rwlock.reader_lock.acquire() try: locked.append(1) await _wait() nlocked.append(len(locked)) await _wait() locked.pop(-1) finally: rwlock.reader_lock.release() finally: rwlock.reader_lock.release() await Bunch(f, N).wait_for_finished() assert max(nlocked) > 1 @pytest.mark.asyncio async def test_writer_recursion(loop, fast_track): rwlock = RWLock(fast=fast_track) N = 5 locked = [] nlocked = [] async def f(): await rwlock.writer_lock.acquire() try: await rwlock.writer_lock.acquire() try: locked.append(1) await _wait() nlocked.append(len(locked)) await _wait() locked.pop(-1) finally: rwlock.writer_lock.release() finally: rwlock.writer_lock.release() await Bunch(f, N).wait_for_finished() assert max(nlocked) == 1 @pytest.mark.asyncio async def test_writer_then_reader_recursion(loop, fast_track): rwlock = RWLock(fast=fast_track) N = 5 locked = [] nlocked = [] async def f(): await rwlock.writer_lock.acquire() try: await rwlock.reader_lock.acquire() try: locked.append(1) await _wait() nlocked.append(len(locked)) await _wait() locked.pop(-1) finally: rwlock.reader_lock.release() finally: rwlock.writer_lock.release() await Bunch(f, N).wait_for_finished() assert max(nlocked) == 1 @pytest.mark.asyncio async def test_writer_recursion_fail(loop): rwlock = RWLock() N = 5 locked = [] async def f(): await rwlock.reader_lock.acquire() try: with pytest.raises(RuntimeError): await rwlock.writer_lock.acquire() locked.append(1) finally: rwlock.reader_lock.release() await Bunch(f, N).wait_for_finished() assert len(locked) == N @pytest.mark.asyncio async def test_readers_writers(loop, fast_track): rwlock = RWLock(fast=fast_track) N = 5 rlocked = [] wlocked = [] nlocked = [] async def r(): await rwlock.reader_lock.acquire() try: rlocked.append(1) await _wait() nlocked.append((len(rlocked), len(wlocked))) await _wait() rlocked.pop(-1) finally: rwlock.reader_lock.release() async def w(): await rwlock.writer_lock.acquire() try: wlocked.append(1) await _wait() nlocked.append((len(rlocked), len(wlocked))) await _wait() wlocked.pop(-1) finally: rwlock.writer_lock.release() b1 = Bunch(r, N) b2 = Bunch(w, N) await asyncio.sleep(0.0001) await b1.wait_for_finished() await b2.wait_for_finished() ( r, w, ) = zip(*nlocked) assert max(r) > 1 assert max(w) == 1 for r, w in nlocked: if w: assert r == 0 if r: assert w == 0 @pytest.mark.asyncio async def test_writer_success(loop): # Verify that a writer can get access rwlock = RWLock() N = 5 reads = 0 writes = 0 async def r(): # read until we achive write successes nonlocal reads, writes while writes < 2: # print("current pre-reads", reads) await rwlock.reader_lock.acquire() try: reads += 1 # print("current reads", reads) finally: rwlock.reader_lock.release() async def w(): nonlocal reads, writes while reads == 0: await _wait() for _ in range(2): await _wait() # print("current pre-writes", reads) await rwlock.writer_lock.acquire() try: writes += 1 # print("current writes", reads) finally: rwlock.writer_lock.release() b1 = Bunch(r, N) b2 = Bunch(w, 1) await b1.wait_for_finished() await b2.wait_for_finished() assert writes == 2 # uncomment this to view performance # print('>>>>>>>>>>>', writes, reads) @pytest.mark.asyncio async def test_writer_success_fast(loop): # Verify that a writer can get access rwlock = RWLock(fast=True) N = 5 reads = 0 writes = 0 async def r(): # read until we achive write successes nonlocal reads, writes while writes < 2: # print("current pre-reads", reads) await rwlock.reader_lock.acquire() try: reads += 1 # print("current reads", reads) await asyncio.sleep(0) finally: rwlock.reader_lock.release() async def w(): nonlocal reads, writes while reads == 0: await _wait() for _ in range(2): await _wait() # print("current pre-writes", reads) await rwlock.writer_lock.acquire() try: writes += 1 # print("current writes", reads) finally: rwlock.writer_lock.release() b1 = Bunch(r, N) b2 = Bunch(w, 1) await b1.wait_for_finished() await b2.wait_for_finished() assert writes == 2 # uncomment this to view performance # print('>>>>>>>>>>>', writes, reads) @pytest.mark.asyncio async def test_writer_success_with_statement(loop): # Verify that a writer can get access rwlock = RWLock() N = 5 reads = 0 writes = 0 async def r(): # read until we achive write successes nonlocal reads, writes while writes < 2: # print("current pre-reads", reads) async with rwlock.reader_lock: reads += 1 # print("current reads", reads) async def w(): nonlocal reads, writes while reads == 0: await _wait() for _ in range(2): await _wait() # print("current pre-writes", reads) async with rwlock.writer_lock: writes += 1 b1 = Bunch(r, N) b2 = Bunch(w, 1) await b1.wait_for_finished() await b2.wait_for_finished() assert writes == 2 # uncomment this to view performance # print('>>>>>>>>>>>', writes, reads) @pytest.mark.asyncio async def test_raise_error_on_with_for_reader_lock(loop, fast_track): rwlock = RWLock(fast=fast_track) with pytest.raises(RuntimeError): with rwlock.reader_lock: pass @pytest.mark.asyncio async def test_raise_error_on_with_for_writer_lock(loop, fast_track): rwlock = RWLock(fast=fast_track) with pytest.raises(RuntimeError): with rwlock.writer_lock: pass @pytest.mark.asyncio async def test_read_locked(loop, fast_track): rwlock = RWLock(fast=fast_track) assert not rwlock.reader_lock.locked async with rwlock.reader_lock: assert rwlock.reader_lock.locked @pytest.mark.asyncio async def test_write_locked(loop, fast_track): rwlock = RWLock(fast=fast_track) assert not rwlock.writer_lock.locked async with rwlock.writer_lock: assert rwlock.writer_lock.locked @pytest.mark.asyncio async def test_write_read_lock_multiple_tasks(loop, fast_track): rwlock = RWLock(fast=fast_track) rl = rwlock.reader wl = rwlock.writer async def coro(): async with rl: assert not wl.locked assert rl.locked await asyncio.sleep(0.2, loop) async with wl: assert wl.locked assert not rl.locked task = asyncio.Task(coro()) await asyncio.sleep(0.1, loop) await task assert not rl.locked assert not wl.locked def test_current_task(loop): with pytest.raises(RuntimeError): _current_task(loop) with pytest.raises(RuntimeError): _current_task() @pytest.mark.asyncio async def test_read_context_manager(loop, fast_track): rwlock = RWLock(fast=fast_track) reader = rwlock.reader_lock assert not reader.locked async with reader: assert reader.locked @pytest.mark.asyncio async def test_write_context_manager(loop, fast_track): rwlock = RWLock(fast=fast_track) writer = rwlock.writer_lock assert not writer.locked async with writer: assert writer.locked @pytest.mark.asyncio async def test_await_read_lock(loop, fast_track): rwlock = RWLock(fast=fast_track) reader = rwlock.reader_lock assert not reader.locked async with reader: assert reader.locked @pytest.mark.asyncio async def test_await_write_lock(loop, fast_track): rwlock = RWLock(fast=fast_track) writer = rwlock.writer_lock assert not writer.locked async with writer: assert writer.locked