Typed task lock for mutually exclusive job types

0
Sign in

Some jobs on a shared accelerator pool must not run alongside jobs of a different kind. Each job runs on its own thread and has one of two types: "gen" or "score". Any number of jobs of the same type may run at once. Jobs of different types must never overlap.

Implement a thread-safe lock class MutexTaskLock:

class MutexTaskLock:
    def acquire(self, task_type: str) -> None: ...  # blocks until the job may run
    def release(self, task_type: str) -> None: ...  # called when the job finishes

Every job calls acquire(t) before it starts and release(t) when it ends.

Requirements

  • Two jobs of different types are never between acquire and release at the same time.
  • Jobs of the same type are not serialised. They can share the lock.
  • A blocked thread must sleep, not spin (no busy-waiting or sleep polling).
  • Many threads call both methods concurrently.
  • Be ready to discuss what happens when one type arrives continuously. Can the other type starve?

Example 1

Threads A (gen) and B (gen) call acquire at t=0 and both return immediately. Thread C (score) calls acquire at t=1 and blocks. A releases at t=2 and C is still blocked. B releases at t=3, the lock is empty, and C's acquire returns.

Example 2

score job S holds the lock. A gen job G arrives and waits. While S is still running, another score job S2 arrives. With a fair lock, S2 waits behind G: S finishes, G runs, then S2 runs. A lock without fairness would admit S2 at once, and G could starve.

Reconstructed from the reported question; details may differ from what interviewers ask.

Microsoft AIMicrosoftOpenAICodingMediumLast asked Aug 2026

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.