C++20 Concurrency: <semaphore>

An efficient mechanism for managing access to a limited resource

CMP
4 min readSep 25, 2023

In one of my previous articles, I discussed a few locking mechanisms that provide mutual exclusion — a synchronization concept where exclusive access to a single shared resource is provided to exactly one thread at a time. This is achieved by allowing threads to acquire and release ownership of a lock, thus locking down the critical section while the owning thread has ownership of the lock.

Using a real-world analogy, imagine a public restroom (a gross example, I know, but bear with me) where there is a single stall for everyone to use. The key to this stall (lock) is held (acquired) by one person (thread) at a time, granting the person exclusive access to the stall (single, shared resource) until the person is done and gives (releases) the key to the next person.

What if there are multiple stalls (let’s say four) instead of just one? Now, it would not make sense to have just one key. Instead, we could have four keys (one for each stall), allowing up to four people to use the stalls at the same time. Each time someone grabs a key and occupies a stall, the number of available keys decreases by one, and increases by one each time someone finishes and leaves their stall.

From a coding perspective, does this mean that we should have four locks to provide mutual exclusion to each individual resource? We could, but this seems awfully inefficient because each lock is an object —…

--

--

CMP

Software engineer specializing in operating systems, navigating the intracicies of the C++ language and systems programming.