Skip to content

Implementing Mutual Exclusion with Semaphores

Introduction to Dijkstra semaphores, the primitives wait and signal based on the integer variable S, and the resolution of mutual exclusion.

In 1968, Edsger W. Dijkstra proposed two fundamental primitives for solving any process interaction and synchronization problem: wait and signal.

These primitives operate on a non-negative integer variable S (called a semaphore):

  • S = 0: red semaphore, meaning the resource is occupied or unavailable.
  • S > 0: green semaphore, meaning the resource is free or events are available.

Edsger W. Dijkstra (1930 - 2002)

Portrait of Edsger W. DijkstraSource: Wikimedia Commons

A Dutch computer scientist and mathematician, Dijkstra was one of the most influential figures in the development of modern computer science. In addition to introducing semaphores and the wait and signal primitives for concurrent programming, he is famous for the shortest-path algorithm named after him: Dijkstra’s algorithm.

🔗 Read the full biography on Wikipedia

To manage access to the shared resource R, processes invoke the two operations on the integer variable S:

  • wait(S) (also called the acquisition operation): checks the state of S. If S < 1, the process blocks or waits. If S >= 1, the process decrements the variable (S--) and enters the critical section.
  • signal(S) (also called the release operation): increments the semaphore variable (S++) to release the resource or unblock any waiting processes.
flowchart TD subgraph Signal ["signal(S) - Release"] S_START([Start]) --> S_INC["S++ (Free)"] --> S_WAKE["Unblock waiting process (if any)"] --> S_END([End]) end subgraph Wait ["wait(S) - Acquisition"] W_START([Start]) --> W_CHECK{"S < 1 ?"} W_CHECK -- Yes --> W_WAIT["Wait / Suspend"] --> W_CHECK W_CHECK -- No --> W_DEC["S-- (Busy)"] --> W_END([End]) end

Diagram created with Mermaid

To protect a shared resource and ensure that only one process at a time can access it, every process that intends to use it must strictly follow a standard protocol composed of three sequential phases:

  1. Resource request (wait): the process invokes the wait(SR) primitive to check the semaphore state and acquire access.
  2. Resource use: the process enters its critical section and performs the necessary operations on the shared resource R.
  3. Resource release (signal): at the end of the operations, the process invokes signal(SR) to restore the free state and allow waiting processes to proceed.

You can directly test semaphore behavior and the interaction of concurrent processes (P1, P2, P3) using the interactive simulator below.

In early theoretical implementations, wait was executed through a continuous loop (for example, while (S < 1) { }), wasting CPU cycles (busy waiting).

In modern operating systems, waiting is handled in a passive manner:

  1. A waiting queue Qs is associated with the semaphore.
  2. If a process executes wait(S) and finds S < 1, the operating system suspends it, moving it from the Running state to the Waiting state and adding its descriptor to the queue Qs.
  3. When another process executes signal(S), the system removes one process from Qs and moves it to the Ready state, avoiding wasted computing resources.

The Atomicity Problem in the wait Operation

Section titled “The Atomicity Problem in the wait Operation”

To understand how a semaphore works in depth, we must analyze what happens internally during wait(S). Acquiring a resource with wait requires two distinct actions in sequence:

  1. Check the semaphore state (verify whether S >= 1).
  2. Update the semaphore (decrement it or suspend the process if S < 1).

To avoid errors, these two operations must be performed atomically (indivisibly). An atomic operation is a block of code that, once started by the processor, must execute to completion without interruption or the possibility of another process interleaving within it.

If the check and subsequent update were not atomic, serious synchronization failures could occur. Imagine this sequence with two concurrent processes (P1 and P2) and a semaphore S initialized to 1:

  • Process P1 performs the check and finds the semaphore free (S = 1). However, before it can change it to 0 (busy), the operating system suspends P1 and assigns the CPU to P2.
  • Process P2 also performs the check, likewise finds the semaphore free (S = 1), and proceeds to occupy it.
  • When P1 resumes execution, believing the resource is free, it occupies it too.

The result is disastrous: both processes access the shared resource simultaneously, completely violating the principle of mutual exclusion.

In future practical Java concurrent-programming exercises, we will see how the language provides native tools (such as the synchronized keyword or wait/notify blocks) that automatically handle this atomicity at the system level, protecting critical sections and preventing hidden conflicts among threads.

Consider two concurrent processes, Q1 and Q2, that access a resource R protected by a semaphore SR initialized to 1. The code structure is as follows:

// Initialization of the semaphore associated with the resource
SR = 1;
// Concurrent execution of processes Q1 and Q2
// --- Process Q1 ---
wait(SR);
// === START CRITICAL SECTION (Use of R) ===
// ... operations on the resource ...
// === END CRITICAL SECTION ===
signal(SR);
// --- Process Q2 ---
wait(SR);
// === START CRITICAL SECTION (Use of R) ===
// ... operations on the resource ...
// === END CRITICAL SECTION ===
signal(SR);

The answers to this page's quizzes are saved in your browser's local storage and remain stored between visits

What does the value S of a semaphore represent?

  • The priority assigned to the running process.
  • The availability of the resource or the number of available events.

    Correct: with S = 0 the resource is unavailable, while with S > 0 it is available.

  • The number of processes currently running on the CPU.

What value is a binary semaphore used as a mutex initialized to?

  • 0, because the resource is initially occupied.
  • 1, because the resource is initially free.

    Correct: a binary mutex has values 0 and 1, and under this convention it is initialized to 1.

  • A negative value, because waiting has already begun.

What is the role of the primitives wait(S) and signal(S)?

  • wait(S) increments the semaphore and signal(S) decrements it.
  • Both only check the state of the CPU without modifying S.
  • wait(S) acquires the semaphore by decrementing it or suspending the process, while signal(S) releases it by incrementing it.

    Correct: wait acquires a resource; signal releases it.

What is the correct protocol for protecting a shared resource?

  • Critical section, wait(S), signal(S).
  • signal(S), resource use, wait(S).
  • wait(S), critical section, signal(S).

    Correct: the process acquires the mutex, uses the resource in the critical section, and finally releases it.

Why must the check and decrement of S inside wait(S) be atomic?

  • To prevent the semaphore from taking values greater than 1.
  • To prevent two processes from simultaneously reading S = 1 and both entering the critical section.

    Correct: if the check and update are interrupted, race conditions and violations of mutual exclusion may occur.

  • To allow the operating system to increase process priority.

Quiz progress

0 / 0 answers to the questions (0%)

0 correct answers