Concurrent Task Execution with Type-Level Exclusion
Data Structure DesignModel answerLast 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:
- Tasks sharing the same category string may execute at the same time
- 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 proceedrelease(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
acquireandreleasecalls 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem extends the classic readers-writers synchronization pattern. Instead of just readers and writers, we have an arbitrary number of categories, each acting like a reader group: threads within one category cooperate, while different categories exclude each other.
The system toggles between two states:
- Idle: no category owns the resource
- Active (category C, n threads): only category C may enter, with n concurrent holders
We maintain this state with two variables protected by a single threading.Condition:
active_type: the category currently holding the resource (orNonewhen idle)count: how many threads of that category are active
Acquire logic: Wait while a different category owns the resource. Once the resource is idle or already matches our category, claim it and increment the counter.
Release logic: Decrement the counter. When it drops to zero, return the system to idle and notify all waiting threads.
Implementation
import threading
class TypeBasedMutex:
def __init__(self):
self._cond = threading.Condition()
self._active_type = None # which category currently holds the resource
self._count = 0 # how many threads of that category are active
def acquire(self, task_type: str) -> None:
with self._cond:
# Wait while a different category owns the resource
while self._active_type is not None and self._active_type != task_type:
self._cond.wait()
# Either idle or our category is active; claim it
self._active_type = task_type
self._count += 1
def release(self, task_type: str) -> None:
with self._cond:
if self._active_type != task_type or self._count == 0:
raise RuntimeError(f"Unmatched release for type {task_type!r}")
self._count -= 1
if self._count == 0:
# Last thread of this category; release ownership
self._active_type = None
self._cond.notify_all()
Why This Works
Mutual exclusion across categories. A thread exits the wait loop only when active_type is None or matches its own category. Before releasing the condition lock, it sets active_type to its category. Therefore, whenever count > 0, all active threads belong to active_type, guaranteeing no cross-category overlap.
Concurrency within a category. If a thread's category already owns the resource, it skips the wait loop entirely and increments the count.
Correctness invariant. count == 0 if and only if active_type is None. Both fields are updated atomically under the condition lock.
Liveness. When the last thread releases, notify_all wakes every waiting thread. Each rechecks the predicate; the first to reacquire the lock claims the resource for its category, and others of that same category immediately join. Threads of other categories return to sleep.
Why notify_all instead of notify. With notify, you might wake a single thread of category B when threads of both B and C are waiting. That B thread proceeds, but other B threads remain asleep even though they could now run, throttling throughput. notify_all ensures all threads of the newly active category wake and proceed together.
No busy-waiting. Blocked threads sleep in wait(), which releases the underlying lock.
Complexity
- Time: Each
acquireandreleaseis O(1) except for time spent blocked. Transitioning to idle wakes all W waiters in O(W) (a thundering herd). - Space: O(1) state plus one queue entry per blocked thread. No per-category bookkeeping; only the active category matters.
Edge Cases and Improvements
Mismatched release. The implementation raises an exception immediately rather than corrupting the count.
Re-entrancy. A thread calling acquire twice for the same category will succeed both times and must call release twice.
Spurious wakeups. Handled by the while loop around wait().
Starvation. If category A threads keep arriving, count may never reach zero, starving category B indefinitely. To prevent this, stop admitting new A threads once another category is waiting. Track waiting counts per category and reject new entrants of the active category when other categories are queued. This trades batching throughput for fairness.
Context manager. For cleaner usage, add:
from contextlib import contextmanager
@contextmanager
def hold(self, task_type):
self.acquire(task_type)
try:
yield
finally:
self.release(task_type)
Common Mistakes
- Using
ifinstead ofwhilearoundwait(), which fails on spurious wakeups - Calling
notify()when multiple threads of the next category should wake - Maintaining separate locks per category, which provides no cross-category exclusion
- Clearing
active_typebeforecountreaches zero, breaking the invariant - Forgetting that
wait()must be inside thewith self._cond:block
What Interviewers Expect
Strong candidates recognize the readers-writers analogy, justify notify_all, and proactively mention starvation. They articulate the invariant between active_type and count and explain why a while loop is necessary. Discussing the fairness vs. throughput trade-off demonstrates depth.