Build a Thread-Safe Dual-Resource Allocator
Data Structure DesignModel answerLast updated
Design a concurrency controller that manages exclusive access to two distinct targets while preventing deadlocks and invalid release calls.
You are tasked with designing a concurrency management component for a multi-threaded system that controls access to two independent, mutually exclusive resources labeled 1 and 2.
Multiple worker threads run in parallel and need to request access to these targets. To maintain correctness and high throughput, your system must abide by the following rules:
- Mutual Exclusion: At any instance, a target can be owned by at most one thread.
- Single-Resource Constraint: A worker thread is strictly forbidden from acquiring both targets simultaneously. If a thread attempts to request a target while already holding any target (including the same one), your implementation must reject the request immediately.
- Correct Ownership: A thread may only release a target that it currently owns. Attempts by non-owners to release a target must be rejected.
- Optimal Throughput: Access to Target 1 and Target 2 must operate independently. Threads competing for Target 1 should not block or contend with threads accessing Target 2.
Implement a DualResourceController class with the following interface:
acquire(resource_id: int) -> None: Blocks the calling thread until the requested target (1or2) becomes available, then marks the calling thread as its owner. If the thread already holds a target, or ifresource_idis invalid, raise an appropriate exception.release(resource_id: int) -> None: Frees the specified target (1or2) and unblocks one waiting thread, if any. Raises an exception if the calling thread does not own the target or ifresource_idis invalid.
Constraints
resource_idwill always be either1or2.- The implementation must be thread-safe, deadlock-free, and resilient against spurious wakeups.
Hints
Hint 1
Consider using independent synchronization primitives per resource to maximize parallelism.
Hint 2
Use thread-local storage to track which resource(s) the current thread holds without introducing global lock contention.
Hint 3
Make sure to guard condition variable waiting inside a loop to handle spurious wakeups and state races.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Architecture
To solve this problem cleanly and with maximum performance, we must address four primary considerations: concurrency, deadlock prevention, ownership validation, and throughput.
1. Fine-Grained Locking for Maximal Throughput
A naive implementation might use a single global mutex for all operations. However, this creates unnecessary contention: a thread acquiring Target 1 would block another thread acquiring Target 2.
To decouple access, we maintain independent synchronization primitives for each target. In Python's threading library, a Condition variable wrapping a Lock per resource provides an ideal mechanism:
- Threads wait on the specific condition variable corresponding to the requested resource.
- Acquiring/releasing Target 1 never contends with Target 2.
2. Thread-Local State for Rule Enforcement
Rule 2 requires that a thread cannot hold both targets at once (or re-acquire the same target). To enforce this without adding cross-resource locks, each thread tracks its owned resources in thread-local storage (threading.local()).
Before acquiring a target, a thread checks its local tracking set:
- If
resource_idis already in the set $\rightarrow$ raiseRuntimeError(cannot re-acquire). - If the set is not empty $\rightarrow$ raise
RuntimeError(cannot hold both targets).
3. Preventing Deadlocks
Deadlocks require four conditions (Coffman conditions): Mutual Exclusion, Hold and Wait, No Preemption, and Circular Wait.
By strictly enforcing Rule 2 (a thread cannot hold a resource while waiting for another), we break the Hold and Wait condition entirely. A blocked thread holds zero resources, making deadlocks impossible.
4. Spurious Wakeups and Ownership Validation
When waiting on a Condition, threads must check the target state inside a while loop:
while self._owner[resource_id] is not None:
cond.wait()
This guarantees safety against spurious wakeups and race conditions where another thread claims the target before the woken thread re-acquires the condition lock.
Python Implementation
import threading
from contextlib import contextmanager
class DualResourceController:
VALID_RESOURCES = {1, 2}
def __init__(self):
# Dedicated Condition variable per resource for non-blocking parallelism across targets
self._conds = {r: threading.Condition(threading.Lock()) for r in self.VALID_RESOURCES}
# Explicit owner tracking for validation
self._owners = {r: None for r in self.VALID_RESOURCES}
# Thread-local storage to track resources held by the calling thread
self._local = threading.local()
def _get_held_resources(self) -> set:
"""Helper to get or initialize the thread-local set of held resource IDs."""
if not hasattr(self._local, "held"):
self._local.held = set()
return self._local.held
def _validate_resource_id(self, resource_id: int):
if resource_id not in self.VALID_RESOURCES:
raise ValueError(f"Invalid resource_id: {resource_id}. Must be 1 or 2.")
def acquire(self, resource_id: int) -> None:
self._validate_resource_id(resource_id)
held = self._get_held_resources()
# Enforce Rule 2: Cannot hold multiple resources or re-acquire the same resource
if resource_id in held:
raise RuntimeError(f"Thread already holds resource {resource_id}.")
if len(held) > 0:
raise RuntimeError("A thread cannot hold both resources simultaneously.")
tid = threading.get_ident()
cond = self._conds[resource_id]
with cond:
# Sleep until resource is free (handles spurious wakeups)
while self._owners[resource_id] is not None:
cond.wait()
self._owners[resource_id] = tid
held.add(resource_id)
def release(self, resource_id: int) -> None:
self._validate_resource_id(resource_id)
tid = threading.get_ident()
cond = self._conds[resource_id]
with cond:
# Enforce Rule 3: Only the current owner can release
if self._owners[resource_id] != tid:
raise RuntimeError(f"Thread {tid} does not hold resource {resource_id}.")
self._owners[resource_id] = None
# Wake up exactly one thread waiting on this resource (avoids thundering herd)
cond.notify()
self._get_held_resources().discard(resource_id)
@contextmanager
def managed_acquire(self, resource_id: int):
"""RAII/Context Manager wrapper ensuring safe release during exceptions."""
self.acquire(resource_id)
try:
yield
finally:
self.release(resource_id)
Complexity Analysis
- Time Complexity:
acquire(id): $O(1)$ constant time work per operation (excluding time spent blocked waiting for the resource).release(id): $O(1)$ constant time work. Unblocks exactly one thread vianotify().
- Space Complexity:
- $O(1)$ total state for the controller.
- $O(1)$ memory per worker thread inside
threading.local(). - $O(W)$ space for condition wait queues where $W$ is the number of currently waiting threads.
Edge Cases & Fault Tolerance
- Re-releasing or Unowned Release:
- Calling
release(1)from a thread that does not own Target 1 immediately raises aRuntimeErrorwithout modifying internal owner state or waking waiters unnecessarily.
- Calling
- Worker Exception Handling:
- If user code crashes while holding a resource, a bare
acquire/releasepair will leak the lock. Providing a context manager (managed_acquire) guaranteesrelease()executes inside afinallyblock.
- If user code crashes while holding a resource, a bare
- Hard Process / Worker Termination:
- In distributed or multi-process systems, if a thread/process is killed (
SIGKILL),finallyblocks will not run. A real-world production solution requires TTL-based leases and heartbeats, where unrenewed locks auto-expire after a timeout period.
- In distributed or multi-process systems, if a thread/process is killed (