Thread-Safe Read-Write Lock (RWLock)
Standard mutexes force read-heavy workloads to bottleneck single-file. A Read-Write Lock allows concurrent simultaneous readers while reserving exclusive access for writers. Synchronizing active reader counts with condition variables prevents race hazards and writer starvation.
import threading
class RWLock:
def __init__(self):
self._lock = threading.Lock()
self._readers = 0
self._cond = threading.Condition(self._lock)
# Thread-Safe Read-Write Lock (RWLock) If 99% of your threads are reading a global configuration table and only 1% are updating it, wrapping that table in `threading.Lock()` slows down execution to single-threaded speeds. 🛡️🔒 An **RWLock** (Read-Write Lock) unlocks maximum concurrency by letting multiple readers inspect memory concurrently. When a writer requests access, new readers wait, allowing the writer to acquire exclusive rights without getting starved by an endless stream of readers. ```python import threading class RWLock: def __init__(self): self._lock = threading.Lock() self._cond = threading.Condition(self._lock) self._readers = 0 self._writer = False ``` ## Pop Quiz Why does an RWLock require tracking waiting writers rather than letting readers acquire locks continuously? - [ ] To prevent writer starvation caused by a non-stop stream of incoming readers. - [ ] Because Python garbage collection purges locks with more than 10 readers. - [ ] To enforce sequential order across multiple CPU L1 cache lines. - [ ] Because reading from Python dicts without write locks raises BufferError. ## Real-World Challenge Implement a thread-safe `RWLock` with writer-preference. It must provide context-manager friendly or explicit methods: `acquire_read()`, `release_read()`, `acquire_write()`, and `release_write()`. Multiple readers must be allowed simultaneously, but writers must have exclusive access. <details> <summary>Solution</summary> ```python import threading class RWLock: def __init__(self): self._lock = threading.Lock() self._ok_to_read = threading.Condition(self._lock) self._ok_to_write = threading.Condition(self._lock) self._readers = 0 self._writers_waiting = 0 self._writer_active = False def acquire_read(self): with self._lock: while self._writer_active or self._writers_waiting > 0: self._ok_to_read.wait() self._readers += 1 def release_read(self): with self._lock: self._readers -= 1 if self._readers == 0: self._ok_to_write.notify() def acquire_write(self): with self._lock: self._writers_waiting += 1 while self._writer_active or self._readers > 0: self._ok_to_write.wait() self._writers_waiting -= 1 self._writer_active = True def release_write(self): with self._lock: self._writer_active = False if self._writers_waiting > 0: self._ok_to_write.notify() else: self._ok_to_read.notify_all() # Verification rw = RWLock() shared_data = {"version": 1} def reader(): rw.acquire_read() val = shared_data["version"] rw.release_read() return val def writer(new_ver): rw.acquire_write() shared_data["version"] = new_ver rw.release_write() t1 = threading.Thread(target=writer, args=(2,)) t2 = threading.Thread(target=reader) t1.start() t2.start() t1.join() t2.join() assert shared_data["version"] == 2 ``` </details>