THINK FIRST·CODE LATER

← All labs

Semaphore simulator with waiting queues

Problem

Simulate counting semaphores with FIFO waiting queues.

Input lines until the end of input:

  • sem NAME value — declare a semaphore;
  • PROC wait NAME — decrement; if the value becomes negative, PROC blocks and joins NAME's queue;
  • PROC signal NAME — increment; if the queue is not empty, wake the first waiting process.

A blocked process cannot execute operations: any operation it issues while blocked prints PROC is blocked, operation ignored.

Output per operation:

A wait mutex -> 0
B wait mutex -> -1, B blocked
A signal mutex -> 0, B woken

For sem lines print nothing. At the end print Final: name=value ... (declaration order) and Blocked at end: B (on full), C (on mutex) in the order they blocked, or Blocked at end: none.

Input:

sem mutex 1
A wait mutex
B wait mutex
C wait mutex
A signal mutex
B signal mutex
C signal mutex

Output:

A wait mutex -> 0
B wait mutex -> -1, B blocked
C wait mutex -> -2, C blocked
A signal mutex -> -1, B woken
B signal mutex -> 0, C woken
C signal mutex -> 1
Final: mutex=1
Blocked at end: none

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.