Semaphore is a useful tool in the prevention of race conditions, semaphore is used to control access to a shared resource by multiple processes in a concurrent system.
First, lets understand, what is a Resource.
In a process ( a program in execution ) a resource can be anything like, a variable holding a reference to some object on the heap, or an open file handle, or an open network socket, and things like that. When they may be used simultaneously by multiple threads, they are termed as a Shared Resource.
When you run multiple threads in a process, there maybe certain sections in your program, where two or more threads might try to access the same resource. So one might mutate a data while other is reading it thereby (the sequence of actions are unpredictable), giving situations of race conditions and stale data. This section of code, is known as Critical Section.
Suppose a library has 10 identical study rooms, to be used by one student at a time. To prevent disputes, students must request a room from the front desk if they wish to make use of a study room. If no rooms are free, students wait at the desk until any room is free. When a student has finished using a room, the student must return to the desk and indicate that one room has become free.
In the simplest implementation, the clerk at the front desk does not need to keep track of which rooms are occupied or who is using them, nor does she know if any given room is actually being used, only the number of free rooms available, which she only knows correctly.
When a student requests a room, the clerk decreases this number. When a student releases a room, the clerk increases this number. Once access to a room is granted, the room can be used for as long as desired, and so it is not possible to book rooms ahead of time.
In this scenario the front desk count-holder represents a counting semaphore, the rooms are the resources, and the students represent processes. The value of the semaphore in this scenario is initially 10. When a student requests a room, he or she is granted access, and the value of the semaphore is changed to 9. After the next student comes, it drops to 8, then 7 and so on. If someone requests a room and the resulting value of the semaphore would be negative, they are forced to wait until a room is freed (when the count is increased from 0).