
Threads and Semaphores: A Ticket Store With a VIP Line
A ticket store admits a limited number of customers at a time. Every customer runs as a separate thread, VIP customers go before everyone else, and the store's earnings have to add up no matter how the threads interleave.
4
customer threads in the sample run
4
semaphores
3
customers allowed in at once
100
earnings, ten tickets at 10
Problem
Understanding the challenge and user needs
Threads that share a room and a cash total collide. Two customers can pass a capacity check at once, two sales can overwrite each other's update, and a regular customer who arrives early can slip in ahead of a VIP who has not arrived yet.
Approach
Strategy and methods used to address the problem
Four semaphores each guard one thing. One counts free places in the store. One protects the earnings total. One holds regular customers at the door until the last VIP has finished, and one protects the count of VIPs served so the last one knows to open that door.
Four semaphores, four jobs
| Semaphore | Starts at | Guards |
|---|---|---|
| Store capacity | Maximum occupancy | How many customers stand inside at once |
| Earnings lock | 1 | The running total of ticket sales |
| VIP bouncer | 0 when VIPs are expected | Regular customers, until the last VIP finishes |
| VIP lock | 1 | The count of VIPs served |
Final Solution
The final design and outcome
In the sample run, with a capacity of three and a ticket price of 10, the two regular customers arrive at 0.0 and 0.2 seconds and wait. Both VIPs enter and leave first, the regulars enter together at 4.5 seconds, and the earnings total 100 for ten tickets.
(opens in a new tab)The sample run, event by event
| Time | Customer | Event | VIP |
|---|---|---|---|
| 1.5 s | Carolina | Enters | Yes |
| 3.5 s | Carolina | Leaves | Yes |
| 4.3 s | Alessandro | Enters | Yes |
| 4.5 s | Alessandro | Leaves | Yes |
| 4.5 s | Borja | Enters | No |
| 4.5 s | Diego | Enters | No |
| 4.9 s | Borja | Leaves | No |
| 7.5 s | Diego | Leaves | No |
Borja and Diego arrive at 0.0 and 0.2 seconds and wait at the door for more than four seconds.
Impact & Validation
Results, learnings, and outcomes
Each rule of the store maps to one semaphore, which keeps the program small enough to reason about and makes each failure traceable to the guard that would have prevented it.

