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 compiler