# 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

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.