Created
March 22, 2023 11:51
-
-
Save jelmervdl/d933f45b4af9404d9a3d4f525276a005 to your computer and use it in GitHub Desktop.
Untested readwritelock for Python threading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ReadWriteLock: | |
def __init__(self): | |
self.readers = 0 | |
self.lock = threading.Condition(threading.Lock()) | |
@contextmanager | |
def lock_for_reading(self): | |
self.lock.acquire() | |
try: | |
self.readers += 1 | |
finally: | |
self.lock.release() | |
try: | |
yield | |
finally: | |
self.lock.acquire() | |
try: | |
self.readers -= 1 | |
finally: | |
self.lock.release() | |
@contextmanager | |
def lock_for_writing(self): | |
self.lock.acquire() | |
self.lock.wait_for(lambda: self.readers == 0) | |
try: | |
yield | |
finally: | |
self.lock.release() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment