Skip to content

Instantly share code, notes, and snippets.

@jelmervdl
Created March 22, 2023 11:51
Show Gist options
  • Save jelmervdl/d933f45b4af9404d9a3d4f525276a005 to your computer and use it in GitHub Desktop.
Save jelmervdl/d933f45b4af9404d9a3d4f525276a005 to your computer and use it in GitHub Desktop.
Untested readwritelock for Python threading
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