Semaphore
In computer science, a semaphore is a variable that controls access to one or more resources. It is a tool developers use to ensure functions only access valid data and run at the right time. A semaphore can prevent a deadlock or race condition by disallowing access to a resource when it is not available.
There are two main types of semaphores in computer programming: binary and counting.
Binary Semaphores
A binary semaphore is a boolean variable that can have only two possible values (0 or 1). It is often used as a lock to restrict access to a function or resource. For example, semaphore A controls function getData(). If A = 0, getData() will not excute. If A = 1, getData() will run. A binary semaphore is also considered a flag or a switch that is either on or off.
Counting Semaphores
A counting semaphore can be any non-negative integer, also known as a whole number. Its value may increase or decrease based on the results of one or more functions. For example, a counting semaphore may keep track of the number of available resources in a resource pool. If the semaphore decrements more than it increments, it will eventually reach 0. A zero value indicates there are no more resources left.
NOTE: A "semaphore" in the real world is a flag or other object used to signal from a distance. For example, a person may hold up a pole from a dock to signal to a ferry captain that he or she would like to come aboard.