pax_global_header00006660000000000000000000000064134057721460014523gustar00rootroot0000000000000052 comment=461f8420336cb00a55dd56f38c00f34718ca7144 aiorwlock-0.6.0/000077500000000000000000000000001340577214600135205ustar00rootroot00000000000000aiorwlock-0.6.0/.coveragerc000066400000000000000000000001021340577214600156320ustar00rootroot00000000000000[run] branch = True source = aiorwlock omit = site-packages, .tox aiorwlock-0.6.0/.gitignore000066400000000000000000000013201340577214600155040ustar00rootroot00000000000000># 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.* coverageaiorwlock-0.6.0/.pyup.yml000066400000000000000000000001231340577214600153120ustar00rootroot00000000000000# Label PRs with `deps-update` label label_prs: deps-update schedule: every month aiorwlock-0.6.0/.travis.yml000066400000000000000000000022571340577214600156370ustar00rootroot00000000000000dist: xenial sudo: required language: python python: - 3.5.3 - 3.6 matrix: include: - python: '3.7' env: MYPY="y" install: - pip install -r requirements-dev.txt - pip install . - pip install codecov script: - | if [ "$MYPY" = "y" ]; then make mypy fi; - make cov after_success: - codecov deploy: provider: pypi user: aio-libs-bot password: secure: "xrYq78Jpw3rfHNc+LDS3IXi0cDZukAgaDuJ+xbkRLwijeSTR8LA9ZFU0OYK2X/+YBrtegBKB15ZkEkjfN702MNaR3wqHGxs+EWVcZc6Yy/lipGTjfGJEiDcIF+wKzFR5wqSL8Hrj66cDnY7dK07jfHc5KswTUizmiYLqGnAJGI+zQVnHCIv6W6iC06LY9eLcBXi514toMN9ku+anNBtzQ14gjW4N0ccCGKaeeAzPsvrMcnpjUh1xOhFG/aTBFpEPLbJ7ZUS87kPabf9/WsLS0tEW8ggSgAZT9GTljbe4I8/Vg14EJCQ4KSpcQ8z9gsf1AAB8XEYIN0jx2ub/c6gYwlazoOln6EE+WbNTHqEx0SiCkHrL7gIOoXEWYG/xPGraYQIi1xD6Yl6nmi0bixUQOgsYGKYb131ycyMJjsHGTdRHnqnja0ev9VIWr5zBu1IKtE/46QRMFYpg5PPAVX211wVsvZwH8plueIA1WRfzwZQoAiZDhQ4Wusql6jFVleeqKy4UldYy3SFoFL0qzlwvm/cx7dkP97NoW8Xtoizz0CJt/BeFGViCaRYbi3Z45rjSaeVWhfcwnIaRdd3FgadxWhJXEohgnoafwCteNz3NGU0lbxBfuOfYEOFgcwdYMzF0KjsGwbfekdAa/ZcLxnuvmJXFXPo/YrWusVw4nBR/9pU=" distributions: sdist bdist_wheel on: tags: true all_branches: true python: 3.7 aiorwlock-0.6.0/CHANGES.rst000066400000000000000000000015371340577214600153300ustar00rootroot00000000000000Changes ------- 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-0.6.0/CONTRIBUTORS.txt000066400000000000000000000001141340577214600162120ustar00rootroot00000000000000Acknowledgements ---------------- Andrew Svetlov https://github.com/asvetlovaiorwlock-0.6.0/LICENSE000066400000000000000000000261041340577214600145300ustar00rootroot00000000000000Apache 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-2016 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-0.6.0/MANIFEST.in000066400000000000000000000002131340577214600152520ustar00rootroot00000000000000include LICENSE include CHANGES.rst include README.rst include Makefile graft aiorwlock graft tests global-exclude *.pyc prune docs/_build aiorwlock-0.6.0/Makefile000066400000000000000000000020031340577214600151530ustar00rootroot00000000000000# Some simple testing tasks (sorry, UNIX only). flake: flake8 aiorwlock tests examples setup.py test: flake pytest -s vtest: pytest -v checkrst: python setup.py check --restructuredtext pyroma: pyroma -d . bandit: bandit -r ./aiorwlock mypy: mypy aiorwlock --ignore-missing-imports --disallow-untyped-calls --no-site-packages --strict cov cover coverage: flake checkrst pyroma bandit 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-0.6.0/README.rst000066400000000000000000000046201340577214600152110ustar00rootroot00000000000000aiorwlock ========= .. image:: https://travis-ci.com/aio-libs/aiorwlock.svg?branch=master :target: https://travis-ci.com/aio-libs/aiorwlock .. image:: https://coveralls.io/repos/jettify/aiorwlock/badge.png?branch=master :target: https://coveralls.io/r/aio-libs/aiorwlock?branch=master .. 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 with async def ---------------------- Requires Python 3.5+ .. code:: python import asyncio import aiorwlock loop = asyncio.get_event_loop() async def go(): rwlock = aiorwlock.RWLock(loop=loop) async with rwlock.writer: # or same way you can acquire reader lock # async with rwlock.reader: pass print("inside writer") await asyncio.sleep(0.1, loop=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. License ------- ``aiorwlock`` is offered under the Apache 2 license. .. _asyncio: http://docs.python.org/3.4/library/asyncio.html .. _patch: http://bugs.python.org/issue8800 aiorwlock-0.6.0/aiorwlock/000077500000000000000000000000001340577214600155125ustar00rootroot00000000000000aiorwlock-0.6.0/aiorwlock/__init__.py000066400000000000000000000201351340577214600176240ustar00rootroot00000000000000import asyncio import sys from collections import deque from asyncio import Task, Future # noqa from typing import Any, List, Tuple, Optional, Callable # noqa try: from typing import Deque except ImportError: Deque = deque # type: ignore Loop = asyncio.AbstractEventLoop OptLoop = Optional[Loop] __version__ = '0.6.0' __all__ = ['RWLock'] PY_35 = sys.version_info >= (3, 5, 3) def current_task(loop: OptLoop = None) -> 'Task[Any]': _loop = loop or asyncio.get_event_loop() # type: Loop if hasattr(asyncio, 'current_task'): t = asyncio.current_task(loop=_loop) else: 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: OptLoop): self._do_yield = not fast self._loop = loop or asyncio.get_event_loop() # type: Loop self._read_waiters = deque() # type: Deque[Future[None]] self._write_waiters = deque() # type: Deque[Future[None]] self._r_state = 0 # type: int self._w_state = 0 # type: int # tasks will be few, so a list is not inefficient self._owning = [] # type: 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 # 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)) if self._do_yield: await asyncio.sleep(0.0, loop=self._loop) 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)) if self._do_yield: await asyncio.sleep(0.0, loop=self._loop) 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)) if self._do_yield: await asyncio.sleep(0.0, loop=self._loop) 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)) if self._do_yield: await asyncio.sleep(0.0, loop=self._loop) 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: self._loop = loop or asyncio.get_event_loop() # type: 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-0.6.0/aiorwlock/py.typed000066400000000000000000000000161340577214600172060ustar00rootroot00000000000000# placeholder aiorwlock-0.6.0/examples/000077500000000000000000000000001340577214600153365ustar00rootroot00000000000000aiorwlock-0.6.0/examples/context_manager.py000066400000000000000000000006301340577214600210650ustar00rootroot00000000000000import 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-0.6.0/examples/simple.py000066400000000000000000000010301340577214600171730ustar00rootroot00000000000000import 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-0.6.0/requirements-dev.txt000066400000000000000000000002241340577214600175560ustar00rootroot00000000000000-e . bandit==1.5.1 flake8-bugbear==18.8.0 flake8-quotes==1.0.0 flake8==3.6.0 pyroma==2.4 pytest-cov==2.6.0 pytest==4.0.1 uvloop==0.11.3 mypy==0.650 aiorwlock-0.6.0/setup.py000066400000000000000000000033311340577214600152320ustar00rootroot00000000000000import os import re import sys from setuptools import setup install_requires = [] if sys.version_info < (3, 5, 3): raise RuntimeError('aiorwlock requires Python 3.5.3+') 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) else: 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.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Operating System :: OS Independent', 'Development Status :: 4 - Beta', 'Framework :: AsyncIO', ] 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, include_package_data=True) aiorwlock-0.6.0/tests/000077500000000000000000000000001340577214600146625ustar00rootroot00000000000000aiorwlock-0.6.0/tests/conftest.py000066400000000000000000000033671340577214600170720ustar00rootroot00000000000000import asyncio import gc import uvloop import pytest @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 loop(request, loop_type, debug): # old_loop = asyncio.get_event_loop() asyncio.set_event_loop(None) if loop_type == 'uvloop': 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.mark.tryfirst def pytest_pycollect_makeitem(collector, name, obj): if collector.funcnamefilter(name): item = pytest.Function(name, parent=collector) if 'run_loop' in item.keywords: return list(collector._genfunctions(name, obj)) @pytest.mark.tryfirst def pytest_pyfunc_call(pyfuncitem): """ Run asyncio marked test functions in an event loop instead of a normal function call. """ if 'run_loop' in pyfuncitem.keywords: funcargs = pyfuncitem.funcargs loop = funcargs['loop'] testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames} loop.run_until_complete(pyfuncitem.obj(**testargs)) return True def pytest_runtest_setup(item): if 'run_loop' in item.keywords and 'loop' not in item.fixturenames: # inject an event loop fixture for all async tests item.fixturenames.append('loop') aiorwlock-0.6.0/tests/test_corner_cases.py000066400000000000000000000060241340577214600207430ustar00rootroot00000000000000import pytest import asyncio import contextlib 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: assert False, ('Inner task expected to be cancelled', task) @pytest.mark.run_loop async def test_get_write_then_read(loop): rwlock = RWLock(loop=loop) 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.run_loop async def test_get_write_then_read_and_write_again(loop): rwlock = RWLock(loop=loop) rl = rwlock.reader wl = rwlock.writer f = loop.create_future() writes = [] async def get_write_lock(): await f with should_fail(.1, loop): async with wl: assert wl.locked writes.append('should not be here') ensure_future(get_write_lock(), loop=loop) async with wl: assert wl.locked async with rl: f.set_result(None) await asyncio.sleep(0.12, loop=loop) # second task can not append to writes assert writes == [] assert rl.locked @pytest.mark.run_loop async def test_writers_deadlock(loop): rwlock = RWLock(loop=loop) 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(.2, loop) async with rl: assert rl.locked task_b = ensure_future(coro(), loop=loop) task_c = ensure_future(coro(), loop=loop) 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.run_loop async def test_readers_cancel(loop): rwlock = RWLock(loop=loop) 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), loop=loop) task_c = ensure_future(coro(rl), loop=loop) 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 aiorwlock-0.6.0/tests/test_rwlock.py000066400000000000000000000325151340577214600176020ustar00rootroot00000000000000import asyncio from aiorwlock import RWLock, current_task import pytest class Bunch(object): """A bunch of Tasks. Port python threading tests""" def __init__(self, f, n, wait_before_exit=False, loop=None): """ 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 = loop or 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(loop=self._loop) self.started.append(tid) try: await f() finally: self.finished.append(tid) while not self._can_exit: await asyncio.sleep(0.01, loop=self._loop) for _ in range(n): t = asyncio.Task(task(), loop=self._loop) self._futures.append(t) async def wait_for_finished(self): await asyncio.gather(*self._futures, loop=self._loop) def do_finish(self): self._can_exit = True async def _wait(loop=None): _loop = loop or asyncio.get_event_loop() await asyncio.sleep(0.01, loop=_loop) def test_ctor_loop_reader(loop): rwlock = RWLock(loop=loop).reader_lock assert rwlock._lock._loop is loop def test_ctor_noloop_reader(loop): asyncio.set_event_loop(loop) rwlock = RWLock().reader_lock assert rwlock._lock._loop is loop def test_ctor_loop_writer(loop): rwlock = RWLock(loop=loop).writer_lock assert rwlock._lock._loop is loop def test_ctor_noloop_writer(loop): asyncio.set_event_loop(loop) rwlock = RWLock().writer_lock assert rwlock._lock._loop is loop @pytest.mark.run_loop async def test_repr(loop): rwlock = RWLock(loop=loop) 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.run_loop async def test_release_unlocked(loop): rwlock = RWLock(loop=loop) with pytest.raises(RuntimeError): rwlock.reader_lock.release() @pytest.mark.run_loop async def test_many_readers(loop, fast_track): rwlock = RWLock(loop=loop, fast=fast_track) N = 5 locked = [] nlocked = [] async def f(): await rwlock.reader_lock.acquire() try: locked.append(1) await _wait(loop=loop) nlocked.append(len(locked)) await _wait(loop=loop) locked.pop(-1) finally: rwlock.reader_lock.release() await Bunch(f, N, loop=loop).wait_for_finished() assert max(nlocked) > 1 @pytest.mark.run_loop async def test_read_upgrade_write_release(loop): rwlock = RWLock(loop=loop) 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.run_loop async def test_reader_recursion(loop, fast_track): rwlock = RWLock(loop=loop, 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(loop=loop) nlocked.append(len(locked)) await _wait(loop=loop) locked.pop(-1) finally: rwlock.reader_lock.release() finally: rwlock.reader_lock.release() await Bunch(f, N, loop=loop).wait_for_finished() assert max(nlocked) > 1 @pytest.mark.run_loop async def test_writer_recursion(loop, fast_track): rwlock = RWLock(loop=loop, 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(loop=loop) nlocked.append(len(locked)) await _wait(loop=loop) locked.pop(-1) finally: rwlock.writer_lock.release() finally: rwlock.writer_lock.release() await Bunch(f, N, loop=loop).wait_for_finished() assert max(nlocked) == 1 @pytest.mark.run_loop async def test_writer_then_reader_recursion(loop, fast_track): rwlock = RWLock(loop=loop, 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(loop=loop) nlocked.append(len(locked)) await _wait(loop=loop) locked.pop(-1) finally: rwlock.reader_lock.release() finally: rwlock.writer_lock.release() await Bunch(f, N, loop=loop).wait_for_finished() assert max(nlocked) == 1 @pytest.mark.run_loop async def test_writer_recursion_fail(loop): rwlock = RWLock(loop=loop) 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, loop=loop).wait_for_finished() assert len(locked) == N @pytest.mark.run_loop async def test_readers_writers(loop, fast_track): rwlock = RWLock(loop=loop, fast=fast_track) N = 5 rlocked = [] wlocked = [] nlocked = [] async def r(): await rwlock.reader_lock.acquire() try: rlocked.append(1) await _wait(loop=loop) nlocked.append((len(rlocked), len(wlocked))) await _wait(loop=loop) rlocked.pop(-1) finally: rwlock.reader_lock.release() async def w(): await rwlock.writer_lock.acquire() try: wlocked.append(1) await _wait(loop=loop) nlocked.append((len(rlocked), len(wlocked))) await _wait(loop=loop) wlocked.pop(-1) finally: rwlock.writer_lock.release() b1 = Bunch(r, N, loop=loop) b2 = Bunch(w, N, loop=loop) await asyncio.sleep(0.0001, loop=loop) 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.run_loop async def test_writer_success(loop): # Verify that a writer can get access rwlock = RWLock(loop=loop) 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(loop=loop) for _ in range(2): await _wait(loop=loop) # 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, loop=loop) b2 = Bunch(w, 1, loop=loop) await b1.wait_for_finished() await b2.wait_for_finished() assert writes == 2 # uncomment this to view performance # print('>>>>>>>>>>>', writes, reads) @pytest.mark.run_loop async def test_writer_success_fast(loop): # Verify that a writer can get access rwlock = RWLock(loop=loop, 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, loop=loop) finally: rwlock.reader_lock.release() async def w(): nonlocal reads, writes while reads == 0: await _wait(loop=loop) for _ in range(2): await _wait(loop=loop) # 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, loop=loop) b2 = Bunch(w, 1, loop=loop) await b1.wait_for_finished() await b2.wait_for_finished() assert writes == 2 # uncomment this to view performance # print('>>>>>>>>>>>', writes, reads) @pytest.mark.run_loop async def test_writer_success_with_statement(loop): # Verify that a writer can get access rwlock = RWLock(loop=loop) 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(loop=loop) for _ in range(2): await _wait(loop=loop) # print("current pre-writes", reads) async with rwlock.writer_lock: writes += 1 b1 = Bunch(r, N, loop=loop) b2 = Bunch(w, 1, loop=loop) await b1.wait_for_finished() await b2.wait_for_finished() assert writes == 2 # uncomment this to view performance # print('>>>>>>>>>>>', writes, reads) def test_raise_error_on_with_for_reader_lock(loop, fast_track): rwlock = RWLock(loop=loop, fast=fast_track) with pytest.raises(RuntimeError): with rwlock.reader_lock: pass def test_raise_error_on_with_for_writer_lock(loop, fast_track): rwlock = RWLock(loop=loop, fast=fast_track) with pytest.raises(RuntimeError): with rwlock.writer_lock: pass @pytest.mark.run_loop async def test_read_locked(loop, fast_track): rwlock = RWLock(loop=loop, fast=fast_track) assert not rwlock.reader_lock.locked async with rwlock.reader_lock: assert rwlock.reader_lock.locked @pytest.mark.run_loop async def test_write_locked(loop, fast_track): rwlock = RWLock(loop=loop, fast=fast_track) assert not rwlock.writer_lock.locked async with rwlock.writer_lock: assert rwlock.writer_lock.locked @pytest.mark.run_loop async def test_write_read_lock_multiple_tasks(loop, fast_track): rwlock = RWLock(loop=loop, 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(), loop=loop) 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=loop) with pytest.raises(RuntimeError): current_task() @pytest.mark.run_loop async def test_read_context_manager(loop, fast_track): rwlock = RWLock(loop=loop, fast=fast_track) reader = rwlock.reader_lock assert not reader.locked async with reader: assert reader.locked @pytest.mark.run_loop async def test_write_context_manager(loop, fast_track): rwlock = RWLock(loop=loop, fast=fast_track) writer = rwlock.writer_lock assert not writer.locked async with writer: assert writer.locked @pytest.mark.run_loop async def test_await_read_lock(loop, fast_track): rwlock = RWLock(loop=loop, fast=fast_track) reader = rwlock.reader_lock assert not reader.locked async with reader: assert reader.locked @pytest.mark.run_loop async def test_await_write_lock(loop, fast_track): rwlock = RWLock(loop=loop, fast=fast_track) writer = rwlock.writer_lock assert not writer.locked async with writer: assert writer.locked