KatInterview

Concurrent Task Execution with Type-Level Exclusion

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencythreadingsynchronization

Last updated

Build a synchronization mechanism allowing tasks of the same type to run together while blocking tasks of different types from overlapping.

You need to build a TypeBasedMutex class that coordinates task execution using string-based categories. The synchronization rules are:

  1. Tasks sharing the same category string may execute at the same time
  2. Tasks with different category strings cannot overlap—if category X is currently executing, category Y must wait until all X tasks complete

Your class should provide:

  • acquire(task_type: str): Blocks until it's safe for this category to proceed
  • release(task_type: str): Marks completion of a task in this category

Requirements:

  • Support any number of distinct category strings
  • Ensure thread-safe operation without spinning or busy loops
  • Assume acquire and release calls are properly paired for each category

Example flow:

mutex = TypeBasedMutex()

# Thread T1: mutex.acquire('read')  → proceeds (claims resource for 'read')
# Thread T2: mutex.acquire('read')  → proceeds (joins 'read' batch)
# Thread T3: mutex.acquire('write') → blocks (waits for 'read' to finish)
# Thread T1: mutex.release('read')
# Thread T2: mutex.release('read')  → last 'read' exits, T3 now proceeds

Hints

Hint 1

Think about how multiple threads of one category can share access while excluding all other categories—this resembles a well-known readers-writers pattern

Hint 2

Track which category currently owns the resource and how many threads are using it; use a condition variable to coordinate waiting

Hint 3

When the last thread of a category releases, the resource becomes free again—wake all waiting threads so the next category can claim it