How semaphore is used to implement mutual exclusion?

A semaphore is a shared variable used to implement mutual exclusion between system processes. It helps solve critical section problems and is a fundamental technique to achieve process synchronization by controlling access to shared resources.

Types of Semaphores

There are two types of semaphores which are as follows −

  • Binary semaphore − Can take only two values, 0 or 1 which means at a time only one process can enter into the critical section. Semaphore is initialized to 1.

  • Counting semaphore − Can take any non-negative value N which means at a time at most N processes can enter into CS. Semaphore is initialized to N.

Semaphore Operations

The critical section is surrounded by P and V operations as follows −

  • P(s) − Wait operation

  • CS − Critical section

  • V(s) − Signal operation

Each of these operations is defined below −

Wait (P) Operation

Wait(P) − Whenever a process enters into CS, first it executes P operation where it decreases semaphore value and if after that s>=0 then enters into CS otherwise added to the waiting queue.

P(Semaphore s)
{
    s = s - 1;
    if (s < 0) {
        block(p);
    }
}

Signal (V) Operation

Signal(V) − When a process exits CS operation V is performed which increases the value of semaphore indicating another process can enter into CS which is currently blocked by P operation.

V(Semaphore s)
{
    s = s + 1;
    if (s >= 0) {
        wakeup(p);
    }
}

Example − Binary Semaphore for Mutual Exclusion

Binary Semaphore Implementation Process 1 Process 2 S = 1 P(s): s = 0 Enter CS V(s): s = 1 P(s): blocked Waiting Enter CS

Lock Variable Implementation

Let us see how the lock variable is used to introduce the mutual exclusion −

It uses a similar mechanism as semaphore but at a time only one process can enter into a critical section and uses lock variable to implement synchronization as below −

while(lock != 0);
lock = 1;
// critical section
lock = 0;

It checks if the lock is equal to 0 then sets the lock to 1 indicating that lock is occupied and then enters into CS. If the lock is not 0, then wait until it is available. When exiting CS set lock back to 0 indicating lock is available and another process can enter into CS.

Comparison

Aspect Lock Variable Semaphore
Implementation User mode Kernel mode
Process Access Only one process Multiple processes (counting)
Values 0 or 1 0 to N (non-negative)
Complexity Simple More complex

Conclusion

Semaphores provide a robust mechanism for implementing mutual exclusion in operating systems. Binary semaphores ensure only one process enters the critical section, while counting semaphores allow controlled access for multiple processes. Semaphores are a generalization of simple lock variables, offering more flexibility and kernel-level implementation.

Updated on: 2026-03-17T09:01:38+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements