Concurrency · 10 / 15 Exercise Medium

Semaphore with a waiting queue

Objective

A semaphore limits how many threads can use a resource at the same time: it has a number of permits. If none are left, the thread waits in a queue until another one releases one. Simulate one. Real threads cannot be created in the browser, so the program simulates the situation in a deterministic way.

Instructions

  • Read the initial free permits and an integer n of events with the format + name (ask for a permit) or - name (release it).
  • Ask: if there are free permits, one is used and it shows name enters (free: k); otherwise the thread goes to the waiting queue and it shows name waits.
  • Release: if there are threads waiting, the first one in the queue gets the permit and it shows name leaves, other enters (free: k) (the free ones do not change). If nobody is waiting, the permit becomes free and it shows name leaves (free: k).
Input
2
6
+ a
+ b
+ c
- a
- b
- c
Output
a enters (free: 1)
b enters (free: 0)
c waits
a leaves, c enters (free: 0)
b leaves (free: 1)
c leaves (free: 2)

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise