Senior · Design · Semaphore permits are not monitor ownership

Design asynchronous mutual exclusion with explicit cancellation and fairness requirements.

Think through your answer before opening the explanation.

Runtime & concurrency

Reveal answer and reasoning

Specify whether fairness is required or whether bounded exclusivity alone is enough. For a SemaphoreSlim-based design, acquire successfully before creating a release owner, avoid release after failed or canceled acquisition, and keep the shared gate alive until all waiters and holders finish. A lease can make release responsibility visible without relying on thread affinity across await.

Test successful entry, pending contention, cancellation before entry, target failure, repeated cleanup, and final permit count using controlled gates. Do not assert FIFO merely because one short run happened to select waiters in launch order. If FIFO grant order is a requirement, use a protocol that explicitly queues and grants requests, with defined canceled-waiter removal and shutdown behavior. The wrong design treats SemaphoreSlim as a reentrant fair monitor or confuses grant order with the order in which asynchronously running operations eventually complete.

What a strong answer covers

  • State exclusivity and fairness separately.
  • Release only an owned successful acquisition.
  • Test canceled waiters, cleanup, and shutdown.

Common pitfall

Inferring a fairness guarantee or release owner from observed scheduling rather than a defined protocol.

Follow-up questions

  1. How would FIFO grant order differ from completion order?
  2. What should disposal do while authorized waiters remain?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions