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 interpreter

4 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. AntyCharacter joke · No posting date

    This problem has 8 hidden tests. I found 9 ways to fail them.

  2. The GraderCharacter joke · No posting date

    Edge case? Never met her.

  3. InterviewerCharacter joke · No posting date

    Walk me through your thinking. No, not out loud. In code. In silence. While I watch.

  4. Me at 2amCharacter joke · No posting date

    My code works. I have no idea why. I am afraid to touch it. I am going to bed.