PythonStudio
Interview Problems

Reader-Writer Lock

hard · lock ownership

Implement ReaderWriterLock(capacity), ignoring the nonnegative capacity argument. This is a nonblocking deterministic lock model: acquire_read(worker) permits many readers only when there is no writer; repeated reads by the same worker are idempotent. acquire_write(worker) succeeds only when nobody holds any lock. A writer's repeated acquire_write is idempotent. A reader cannot upgrade, and a writer cannot acquire_read. Failed calls return False without changing state. release(worker) releases that worker's read or write lock and returns whether it owned one. state() returns {'readers': sorted worker names, 'writer': name or None}. No waiting/fairness guarantee, real threads, or timing is required. Examples (JSON; null means Python None): Input: {"capacity": 0, "operations": [["acquire_read", ["b"]], ["acquire_read", ["a"]], ["acquire_write", ["w"]], ["state", []]]} Output: [true, true, false, {"readers": ["a", "b"], "writer": null}] Input: {"capacity": 0, "operations": [["acquire_write", ["w"]], ["acquire_read", ["r"]], ["release", ["w"]], ["acquire_read", ["r"]]]} Output: [true, false, true, true]

Starter code

class ReaderWriterLock:

    def __init__(self, capacity: int):
        """Implement this operation according to the statement."""
        pass

    def acquire_read(self, worker: str) -> bool:
        """Implement this operation according to the statement."""
        pass

    def acquire_write(self, worker: str) -> bool:
        """Implement this operation according to the statement."""
        pass

    def release(self, worker: str) -> bool:
        """Implement this operation according to the statement."""
        pass

    def state(self) -> dict:
        """Implement this operation according to the statement."""
        pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python compiler