Katkat

Coordinate workers across two exclusive targets

TeslaSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to manage concurrent resources using synchronization primitives, ensuring workers can safely alternate between two exclusive tasks while maintaining thread safety.

Problem Statement

You are managing a task system with two distinct, exclusive resources: Resource A and Resource B. You have N worker threads. Each worker must perform a sequence of tasks that requires acquiring these resources in specific, alternating combinations.

Implement a controller class ResourceCoordinator that manages these two resources. The system must adhere to the following rules:

  1. At any given time, a resource can only be held by one worker.
  2. A worker cannot hold both resources simultaneously. If a worker requires a resource that is currently held, it must block until the resource becomes available.
  3. Implement the following methods:
    • acquire(resource_id): Blocks until the specified resource (1 or 2) is free, then marks it as busy.
    • release(resource_id): Marks the specified resource as free and signals waiting workers.

Constraints

  • resource_id will only be 1 or 2.
  • Ensure the implementation is thread-safe and prevents deadlocks.
  • Optimize for high throughput so that workers do not stay blocked longer than necessary.

Example Usage

coordinator = ResourceCoordinator()

# Thread 1
coordinator.acquire(1)
# Do work with Resource 1
coordinator.release(1)

# Thread 2
coordinator.acquire(2)
# Do work with Resource 2
coordinator.release(2)

Edge Cases to Consider

  • Multiple threads requesting the same resource simultaneously.
  • A thread attempting to release a resource it does not hold.
  • Sudden termination of a thread while holding a resource (how would you ensure the resource is released?).

Hints

Hint 1

Use standard synchronization primitives like Mutexes or Semaphores to gate access to the individual resources.

Hint 2

A binary semaphore or a Lock for each resource will ensure that only one thread can hold a specific resource at a time.

Hint 3

To handle thread crashes, consider a try-finally block or a context manager pattern to ensure that `release` is called even if the worker logic encounters an exception.

Follow-up questions

  • How would you modify your design if a worker needs to acquire both resources simultaneously without causing a deadlock?
  • If you were tasked with monitoring resource utilization, where would you add instrumentation to track total idle time versus busy time?
  • How does your implementation change if the number of resources scales from 2 to K, where K is a large integer?