# What is the abstract idea of a semaphore and how can we use it to implement mutual exclusion?

So I've got this so far to try and wrap my head around the abstract idea of a semaphore:

A semaphore is a variable or abstract datatype (commonly an integer), used to control access to a common resource by multiple processes in a concurrent system.

I'm not sure that this definition fully encompasses the full idea of semaphores.

As well as this, I'm not sure how we could use them to implement mutual exclusion.

Any notes to help me understand this concept is appreciated!

• That's not a definition. It's a description of purpose that many things fulfill, and it's not the only purpose a semaphore serves. Please look up a precise definition of the exact thing you're working with. – Raphael Apr 29 '17 at 9:39
• Anyway, what have you tried and where did you get stuck? – Raphael Apr 29 '17 at 9:40
• @Raphael I know about the wait and post methods but i'm more interested in figuring out the idea behind using semaphores, rather than actually implementing them – rshah Apr 29 '17 at 9:41
• If that's the only sentence you read so far, of course you wouldn't have a good handle on it. Did you try google.com/search?q=semaphore instead? There are so many descriptions and so many examples of so many cases in so many languages. I mean, there's even one right over on SO on the first page of results. – Jason C Apr 29 '17 at 14:18

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.

• @rshah: thanks for the edit. English isn't my first language. – EL Dendo Apr 29 '17 at 11:03