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

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

os7-2-data-1.txt

sem mutex 1
A wait mutex
B wait mutex
C wait mutex
A signal mutex
B signal mutex
C signal mutex
What your program must print for os7-2-data-1.txt
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

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < os7-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content os7-2-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

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.