Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Thread-Safe Shared Resource Manager

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Thread-Safe Shared Resource Manager. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

CMT DriveWell services may share a bounded pool of reusable resources. Implement a thread-safe resource manager that allocates the smallest available resource identifier and safely returns resources to the pool.

The manager must support non-blocking acquisition. If no resource is available, acquisition returns -1. Releasing an unknown, already released, or out-of-range identifier returns False and must not change the pool.

Formal Specification

Implement process_resource_operations(operations, capacity):

  • operations is a list of commands. An acquire command is ["acquire"]; a release command is ["release", resource_id].
  • capacity is the number of resources, identified by integers from 0 through capacity - 1.
  • Return one result for every command. An acquire result is the allocated integer ID or -1. A release result is True or False.
  • The underlying manager must use synchronization so concurrent calls cannot allocate the same resource or corrupt its state.

Constraints

  • 1 <= capacity <= 10^5
  • 0 <= operations.length <= 2 * 10^5
  • Each operation is either ["acquire"] or ["release", resource_id]
  • resource_id may be outside the valid range
  • The manager may be accessed concurrently by multiple threads

Function Signature

def process_resource_operations(operations, capacity):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output