Semaphore Simulator

medium · os, synchronization

Semaphore Simulator

Simulate a counting semaphore with FIFO wakeup.

Types

type Op struct {
    Thread int
    Kind   string // "P" or "V"
}

func SimulateSemaphore(initial int, ops []Op) []int

Rules

  • The semaphore count starts at initial.
  • P (wait): if count > 0, decrement and the thread acquires immediately.
    • Otherwise, the thread blocks and is enqueued (FIFO).
  • V (signal): if the wait queue is non-empty, dequeue one thread and let it acquire immediately.
    • Otherwise, increment the count.

Output

Return the list of thread IDs in the order they acquire the semaphore. This includes acquisitions from both immediate P and wakeups from V.

Notes

  • The input sequence is valid: blocked threads do not issue further ops until unblocked.
Run tests to see results
No issues detected