2. Semaphore
Provides solution to impose Mutual exclusion among concurrently executing
processes.
Semaphore consists of an integer variable S
S is shared by concurrently executing processes
S protected variable: accessed and modified by two operations wait() and signal().
Value of S denotes number shared resources
Wait() is indicated by symbol P
Signal() is indicated by V
P and V are called as semaphore primitives
Each semaphore has a queue associated with it called as semaphore queue.
3. semaphore
Each P operation decrements value of count by 1.
Each V operation increments value of count by 1.
P and V ensures that only one process enters in its critical section.
All other processes waiting to enter in their critical section wait in semaphore
queue
Semaphore ensures that no process go into busy waiting.
Moving the process to semaphore queue is called as block operation. In which
process changes state from running state to waiting state.
Removing process from semaphore queue and place into ready queue called as
wakeup operation.
4. Semaphores
Types of Semaphores
There are two main types of semaphores i.e. counting semaphores and binary
semaphores
Counting Semaphores These are integer value semaphores and have an
unrestricted value domain. These semaphores are used to coordinate the resource
access, where the semaphore count is the number of available resources. If the
resources are added, semaphore count automatically incremented and if the
resources are removed, the count is decremented.
5. Semaphore
Binary Semaphores The binary semaphores are like counting semaphores but
their value is restricted to 0 and 1. The wait operation only works when the
semaphore is 1 and the signal operation succeeds when semaphore is 0. It is
sometimes easier to implement binary semaphores than counting semaphores.
6. semaphore
Semaphore is defined as
typedef struct
{
int count;
struct processqueue queue;
}semaphore;
7. Counting Semaphore
Wait is defined as
wait(semaphore S)
{
S.count--;
if(S. count<0)
{
//Perform block operation
and move the process to
semaphore queue
block();
}
}
signal is defined as
signal(semaphore S)
{
S.count++;
if(S. count<=0)
{
//Perform wakeup operation
and move the process
to ready queue
wakeup();
}
}
8. semaphore
Critical section can be accessed by
while(TRUE)
{
wait(S);
//Critical Section
signal(S);
//Remainder section
}
9.
10. Binary Semaphore
Wait operation
wait(Semaphore S)
{
if(S.count==1)
{
s.count=0
}
else
{
//block this process and place into
Semphore queue
block();
}
}
Signal operation
signal(Semaphore S)
{
if(Semaphore queue is empty)
{
s.count=1
}
else
{
//select the process from semaphore
queue and wakeup();
block();
}
}
13. Disadvantages
Semaphore with waiting queue may result in situation where two or more
processes waiting indefinitely. These processes are called as deadlocked.
Priority inversion occurs: Low priority process executes on high priority process.