Skip to content
Threads and Semaphores: A Ticket Store With a VIP Line

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.

ConcurrencyThreadsSemaphoresPython

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.

Each customer thread waits at the VIP door if it has to, takes a place in the store, pays under the earnings lock, and, if it is the last VIP, opens the door for everyone else.
The store creates its semaphores, starts a thread per customer, and waits for all of them to finish.

Four semaphores, four jobs

SemaphoreStarts atGuards
Store capacityMaximum occupancyHow many customers stand inside at once
Earnings lock1The running total of ticket sales
VIP bouncer0 when VIPs are expectedRegular customers, until the last VIP finishes
VIP lock1The 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.

Terminal output of the ticket store simulation (opens in a new tab)
The simulation's output for four customers: both VIPs first, then the two regular customers together.

The sample run, event by event

TimeCustomerEventVIP
1.5 sCarolinaEntersYes
3.5 sCarolinaLeavesYes
4.3 sAlessandroEntersYes
4.5 sAlessandroLeavesYes
4.5 sBorjaEntersNo
4.5 sDiegoEntersNo
4.9 sBorjaLeavesNo
7.5 sDiegoLeavesNo

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.