Semaphore
TechniqueConcurrencyJuniorMidUpdated
Counter with atomic acquire/release: lets at most N permits be held simultaneously. Generalizes the mutex (N=1).
When to Use Semaphore
Bounding concurrent access to a finite resource pool: DB connections, outbound HTTP slots, GPU memory. Also for classic signaling patterns.
In Practice
Java's
Semaphore, Python's threading.Semaphore, Linux kernel struct semaphore. Most JDBC connection pools (HikariCP) use a semaphore-like counter to cap in-flight connections.Sketch
Java
Semaphore dbSlots = new Semaphore(10);
public Row query(String sql) throws InterruptedException {
dbSlots.acquire();
try {
return runQuery(sql);
} finally {
dbSlots.release();
}
}How Semaphore Comes Up in Interviews
Scenario
Your service can open at most 20 connections to a downstream DB or it will be throttled. Hundreds of request threads need to share those slots, blocking briefly when none are free. Which primitive is the direct fit?
A semaphore initialized with 20 permits is exactly 'N concurrent holders allowed.' A mutex would serialize all DB calls (N=1); rwlock is the wrong axis (read vs. write); CAS is the wrong tool for resource capacity.