Multithreading: Semaphores

This post is all about theory…you’ve been warned :,,)

Semaphores have different usage semantics than mutexes. A thread can perform two operations over a semaphore: you can run a put or a take. Internally, the semaphore maintains a count of the numbers of takes and puts through the use of a counter: whenever a thread tries to take take from a semaphore, it will succeed and decrement the counter *if*, at that moment, the counter is bigger than 0. Putting performs the reverse operation. Both operations (put and take) are atomic.

As you might expect, you can “set up” the counter whenever you create a new semaphore, limiting the maximum number of threads which can simultaneously access the resource protected by that semaphore. Since a semaphore is also a kernel object, the same principles that we’ve talked about in the past still hold. A semaphore is signaled whenever its internal counter’s value is non zero. A semaphore is in the non signaled state whenever the it reaches 0. Trying to take from a non signaled semaphore (ie, “acquiring” from a semaphore where its internal counter is 0) blocks until the counter is increased (which will only happen when another thread performs a put operation – or, if you prefer the acquire/release terminology, when another thread releases the semaphore).

Unlike mutexes, semaphores don’t support the concept of ownership. This means that you can have a thread putting and other taking (without having put before). Like mutexes, semaphores will only wake as many threads as the ones that can “acquire” the semaphore (ie, if you’ve got 4 threads blocked  and the semaphore’s counter has seen its value pop up to 2, then only the first 2 threads will be awakened) – recall that mutexes will only wake a single thread at a time.

In the “real world”, you’ll tend to use semaphores when you need to protect access to finite resources. A good example of the kind of resources protected by a semaphore are pools (of objects), where you can only allow x threads at a time. Publisher/subscriber scenarios are also scenarios that might benefit from using semaphores.

Ok, I guess that this is more than enough for an introduction to this topic. The next post will present some code snippets of its usage.


~ by Luis Abreu on May 15, 2009.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: