A semaphore is a counter, that counts the number of processes that have access to a resource. If a resource can service n processes, n is decremented each time a process accesses the resource, and increments it when the process no longer needs the resource. When n reaches zero, the access of the resource is denied.
A real life example will make things clear: imagine a public toilet with 5 toilets (n=5). At the entrance there is a guard (the semaphore). If some one wants to enter the guard looks at n. if n > 0 the guard let the visitor in and decrements n. If someone comes out n is incremented. Only if n=0 the guard will block the entrance until someone leaves.
Consider a binary semaphore, where n = 1
. This semaphore works as a flag which is activated when the resource is in use or not, and can be used to protect a critical section. When a process wants to enter the critical section, it first looks at the ‘flag’ to find out if the critical section is being used by another process. If not, the process enters and raises the flag, preventing the other processes to enter. The flag is unset when the process leaves, and therefore ensures mutual exclusion.