KatInterview

Build a Thread-Safe Dual-Resource Allocator

Data Structure DesignModel answer
HardModel answerData Structure Designconcurrencymultithreadinglocks

Last 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:

  1. Mutual Exclusion: At any instance, a target can be owned by at most one thread.
  2. 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.
  3. Correct Ownership: A thread may only release a target that it currently owns. Attempts by non-owners to release a target must be rejected.
  4. 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 (1 or 2) becomes available, then marks the calling thread as its owner. If the thread already holds a target, or if resource_id is invalid, raise an appropriate exception.
  • release(resource_id: int) -> None: Frees the specified target (1 or 2) and unblocks one waiting thread, if any. Raises an exception if the calling thread does not own the target or if resource_id is invalid.

Constraints

  • resource_id will always be either 1 or 2.
  • 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.