CSharpFeeds - All your C# feeds in one place.

Sponsors

Friday, May 15, 2009

Multithreading: Semaphores

by luisabreu via LA.NET [EN] on 5/15/2009 2:18:28 PM

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.


email it!bookmark it!digg it!

Original Post: Multithreading: Semaphores

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us