How does semaphore work?

Greg picture Greg · Aug 3, 2009 · Viewed 35.2k times · Source

Can the semaphore be lower than 0? I mean, say I have a semaphore with N=3 and I call "down" 4 times, then N will remain 0 but one process will be blocked?

And same the other way, if in the beginning I call up, can N be higher than 3? Because as I see it, if N can be higher than 3 if in the beginning I call up couple of times, then later on I could call down more times than I can, thus putting more processes in the critical section then the semaphore allows me.

If someone would clarify it a bit for me I will much appreciate.

Greg

Answer

Jon Skeet picture Jon Skeet · Aug 3, 2009

(Using the terminology from java.util.concurrent.Semaphore given the Java tag. Some of these details are implementation-specific. I suspect your "down" is the Java semaphore's acquire() method, and your "up" is release().)

Yes, your last call to acquire() will block until another thread calls release() or your thread is interrupted.

Yes, you can call release() more times, then down more times - at least with java.util.concurrent.Semaphore.

Some other implementations of a semaphore may have an idea of a "maximum" number of permits, and a call to release beyond that maximum would fail. The Java Semaphore class allows a reverse situation, where a semaphore can start off with a negative number of permits, and all acquire() calls will fail until there have been enough release() calls. Once the number of permits has become non-negative, it will never become negative again.