The most usual use of a semaphore is actually as a mutex. It goes like this:
The purpose of a mutex is to act as a lock, so two processes or threads can't hold the lock at the same time, ever. The mutex has a counter, initialized to 1. When a process/thread wants to acquire the lock, it decrements the counter. To release it, it increments the counter. **but**, if it tries to acquire the lock and the counter is already at 0, it goes to sleep until whoever had the lock releases it, then decrements the counter and goes about its business.
So with a mutex, the counter is always 1 or 0.
A semaphore can be initialized to values higher than 1, say n. In this case, only up to n processes/threads can hold the semaphore at one time. There aren't a ton of situations where this is useful.
|