# Introduction to Semaphores

In 1965, Dijkstra proposed a new and very significant technique for managing concurrent processes by using the value of a simple integer variable to synchronize the progress of interacting processes. This integer variable is called semaphore. So it is basically a synchronizing tool and is accessed only through two low standard atomic operations, wait and signal designated by `P(S)` and `V(S)` respectively.

In very simple words, semaphore is a variable which can hold only a non-negative Integer value, shared between all the threads, with operations wait and signal, which work as follow:

``````P(S): if S ≥ 1 then S := S - 1
else <block and enqueue the process>;

V(S): if <some process is blocked on the queue>
then <unblock a process>
else S := S + 1;``````

The classical definitions of wait and signal are:

• Wait: Decrements the value of its argument `S`, as soon as it would become non-negative(greater than or equal to `1`).
• Signal: Increments the value of its argument `S`, as there is no more process blocked on the queue.

## Properties of Semaphores

1. It's simple and always have a non-negative Integer value.
2. Works with many processes.
3. Can have many different critical sections with different semaphores.
4. Each critical section has unique access semaphores.
5. Can permit multiple processes into the critical section at once, if desirable.

## Types of Semaphores

Semaphores are mainly of two types:

1. Binary Semaphore:

It is a special form of semaphore used for implementing mutual exclusion, hence it is often called a Mutex. A binary semaphore is initialized to `1` and only takes the values `0` and `1` during execution of a program.

2. Counting Semaphores:

These are used to implement bounded concurrency.

## Example of Use

Here is a simple step wise implementation involving declaration and usage of semaphore.

``````Shared var mutex: semaphore = 1;
Process i
begin
.
.
P(mutex);
execute CS;
V(mutex);
.
.
End;``````

## Limitations of Semaphores

1. Priority Inversion is a big limitation of semaphores.
2. Their use is not enforced, but is by convention only.
3. With improper use, a process may block indefinitely. Such a situation is called Deadlock. We will be studying deadlocks in details in coming lessons.