6.3 Counting semaphores
A counting semaphore is a type of lock that allows you to limit the number of processes
that can concurrently access a resource to some fixed number. You can think of the
lock that we just created as being a counting semaphore with a limit of 1. Generally,
counting semaphores are used to limit the amount of resources that can be used at
Like other types of locks, counting semaphores need to be acquired and released.
First, we acquire the semaphore, then we perform our operation, and then we release
it. But where we’d typically wait for a lock if it wasn’t available, it’s common to fail
immediately if a semaphore isn’t immediately available. For example, let’s say that we
wanted to allow for five processes to acquire the semaphore. If a sixth process tried to
acquire it, we’d want that call to fail early and report that the resource is busy.
We’ll move through this section similarly to how we went through distributed locking
in section 6.2. We’ll build a counting semaphore piece by piece until we have one
that’s complete and correct.
Let’s look at an example with Fake Game Company. With the success of its marketplace
continuously growing, Fake Game Company has had requests from users wanting
to access information about the marketplace from outside the game so that they can
buy and sell items without being logged into the game. The API to perform these operations
has already been written, but it’s our job to construct a mechanism that limits
each account from accessing the marketplace from more than five processes at a time.
After we’ve built our counting semaphore, we make sure to wrap incoming API
calls with a proper acquire_semaphore() and release_semaphore() pair.