Thread-Safe Counter

easy · lock ownership

Implement LockedCounter(initial). This is a deterministic model of a counter's critical section, not an OS-thread exercise. Each operation is atomic. acquire(worker) returns True if the lock is free or already owned by worker, otherwise False. increment(worker, delta) changes the counter only when worker owns the lock and returns whether it succeeded. release(worker) succeeds only for the owner. value() reads the counter without changing it. Re-acquiring is idempotent, not recursive: one release unlocks it. Worker names are nonempty strings; delta and initial are integers. The test's capacity field is the initial value. Never use real threads or wall-clock sleeps. Examples (JSON; null means Python None): Input: {"capacity": 0, "operations": [["increment", ["a", 1]], ["acquire", ["a"]], ["increment", ["a", 2]], ["value", []]]} Output: [false, true, true, 2] Input: {"capacity": 3, "operations": [["acquire", ["a"]], ["acquire", ["b"]], ["increment", ["b", 8]], ["release", ["a"]], ["acquire", ["b"]], ["increment", ["b", -1]], ["value", []]]} Output: [true, false, false, true, true, true, 2]

Starter code

class LockedCounter:

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

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

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

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

    def value(self) -> int:
        """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.