Semaphores: How to Establish Order Among Concurrently Running Tasks

In this blog post, we’ll examine why synchronization is necessary when multiple tasks use the same resource and how semaphores control access, using everyday examples.

 

Why Do Problems Arise When Tasks Are Processed Simultaneously?

Suppose that just as you receive a message from your mom saying, “There’s curry in the fridge,” you also receive a message from your girlfriend saying, “Let’s break up.” Receiving both pieces of news at once is disconcerting enough, but what if the screen displayed the message, “Son, we’re breaking up. Enjoy the curry in the fridge and live well”? You can understand this confusion by imagining a situation where the contents of two different messages are written to the same output space without any coordination. While this example doesn’t exactly describe how a real-world messaging app works, it serves as an analogy to illustrate why rules are necessary when multiple tasks use shared resources.
Programs running on a computer are called “processes.” The operating system allocates processing time among multiple processes and manages their execution. In an environment with a single processing stream, multiple tasks can be executed alternately at short intervals to make it appear as if they are running simultaneously. In environments with multiple processing cores, tasks may actually execute at the exact same moment. In either case, problems can arise if the processes of reading or modifying the same data overlap. “Synchronization” is the process of coordinating these tasks so that they proceed in the correct order and under the correct conditions.
Let’s consider a bank account as an example where the outcome is clearer than with text messages. Suppose two people are trying to withdraw 100,000 won each from an account with a balance of 200,000 won, using different ATMs. To understand the principle, let’s simplify the withdrawal process into three steps: “read balance → subtract withdrawal amount → save new balance.” If the first ATM reads a balance of 200,000 won and the second ATM reads the same balance before the first ATM saves the new balance, both ATMs will subtract 100,000 won from 200,000 won. What happens next when both ATMs save 100,000 won as the new balance? Although a total of 200,000 won in cash has been dispensed, the account is still recorded as having 100,000 won remaining. This creates a discrepancy between the correct final balance of 0 won and the recorded 100,000 won.
The problem does not lie in the subtraction itself. It lies in the fact that both operations calculated based on the same old balance and overwrote each other’s results. If the order had been such that the first withdrawal updated the balance and the second withdrawal then read that balance, the balance would have changed from 200,000 won to 100,000 won, and then back to 0 won.

 

Shared resources require access rules

A situation where the result varies depending on the execution order or timing of operations accessing a shared resource is called a “race condition.” In the ATM example above, the final record differs depending on which ATM reads and saves the balance and when. Since such errors may go unnoticed if the execution order happens to align correctly, it is difficult to judge the system as safe based solely on the fact that it has worked normally a few times.
In this example, the part that needs to be protected is the sequence of code that reads the balance, subtracts the withdrawal amount, and saves the new balance. A section of code like this, which handles shared resources and must control concurrent access, is called a “critical section.” If a task is within a critical section that updates the balance of the same account, other tasks can be made to wait until the preceding task is complete. This property—which ensures that only one task at a time executes within a critical section protecting the same resource—is called “mutual exclusion.”
Applying mutual exclusion does not mean that all tasks on a computer must be executed one at a time. Rather, it involves establishing access rules for parts that could conflict with each other, such as tasks that modify the balance of the same account. Unrelated tasks can continue to run. The key to synchronization lies in precisely determining which tasks share what resources and at which points they must wait.

 

A semaphore is a device that counts access permissions

A “semaphore” is one of the basic tools used to implement this synchronization. Proposed in the 1960s by Dutch computer scientist Edsger Dijkstra, it uses integer values and operations that safely modify those values to control the progress of tasks. When managing resource usage, it is easiest to understand this integer as the “number of remaining access permits.”
Imagine a room with a single printer. In this room, it has been decided that only one person may use the printer at a time. A security guard keeps a single key and hands it to a user when they arrive. While the user has the key and is inside the room, anyone else who arrives must wait. Once the first person finishes printing and returns the key, one of the waiting people receives the key and enters the room.
In this analogy, the printer is a shared resource, and the process of using the printer is the critical section. The number of keys held by the guard corresponds to the value of the semaphore. If a key is available, the value is 1; if no key is available because someone is using the printer, the value is 0. A semaphore is not just an ordinary variable representing this number. It is a synchronization tool that provides the entire procedure for checking and granting access.
These procedures are traditionally referred to as P() and V(). Let’s call the semaphore’s value S. Explained in a way that ensures the value never becomes negative, the two operations work as follows.

P(S) decrements the value of S by 1 if S is greater than 0, then proceeds to the next task. If S is 0, it waits until permission can be obtained.

V(S) returns one permission. If there are waiting tasks, it allows one of them to obtain permission and proceed.

The important condition here is not “0 or greater” but “greater than 0.” A value of 0 means there are no permissions to grant, so no new tasks should be allowed to pass.
Another important point is that checking for permission and acquiring it are performed atomically. “Atomic” means that the operation is processed as a single, indivisible action from the perspective of other tasks. It is not acceptable for two people to look at a single key, each conclude, “Since the key is there, I can go in,” and then enter together. A semaphore ensures that once a task acquires permission, no other task can acquire that same permission again.
By setting the semaphore’s initial value to 1, mutual exclusion can be implemented if all tasks using the same resource follow the sequence “P(S) → critical section → V(S).” The task that executes P(S) first obtains permission to enter, while other tasks wait. Once the task completes the critical section and returns permission via V(S), the next task can proceed.

 

When There Is One Permission vs. Multiple Permissions

Semaphores are not used solely to protect a single resource. They can also be used to limit the number of concurrent users when providing multiple resources of the same type.
A “binary semaphore,” which is limited to the values 0 and 1, represents two states: permission granted or permission denied. As in the earlier example of the print room, if only one task is allowed at a time, the initial value is set to 1. In contrast, a “counting semaphore” counts the number of available permissions. For example, if there are three printers that can be used independently, the initial value can be set to 3. Once three tasks have each obtained permission, the value becomes 0, and the fourth task waits until someone finishes using the resource.
In this case, the semaphore manages how many permissions remain. Assigning which of the three printers to use requires separate management. The role of a counter semaphore is to prevent more than a specified number of tasks from using the resource simultaneously.

 

Even if two operations are safe, proper usage must still be followed

Just because P() and V() operate atomically does not automatically guarantee the correctness of the entire program. Race conditions can still occur if part of the code that needs protection is placed outside the critical section, or if a task accesses a shared resource without going through the semaphore. Problems also arise if the order of acquiring and releasing permits is written incorrectly.
Suppose we execute “P(S) → critical section → P(S)” on a semaphore with an initial value of 1. Since the first P(S) used the single available permission, the value is now 0. If the second P(S) is called after the critical section is completed, that task will pause, requesting one more permission instead of returning it. If other tasks are also waiting at P(S) and no one can execute V(S), the system falls into a deadlock where no task can proceed further. It is as if a person holding a key is waiting for another key without returning the one they already have.
Conversely, if V(S) is called before entering the critical section, the mistake of acquiring an additional permission is made before the current one has been released. When using a standard counter semaphore initialized to 1 for mutual exclusion, this error creates the possibility for two or more tasks to enter simultaneously. Furthermore, if a permission is not released when an error occurs in the critical section or when a task is terminated prematurely, other tasks may continue to wait.
To use a semaphore correctly, it must be clear what the shared resource is, how many tasks are allowed simultaneously, and where permission is acquired and returned. The rules for borrowing and returning the “key” are simple, but they are effective only if every task adheres to them. A semaphore turns this agreement into an executable procedure, helping multiple tasks proceed concurrently without corrupting each other’s results.

 

About the author

Cam Tien

I love things that are gentle and cute. I love dogs, cats, and flowers because they make me happy. I also enjoy eating and traveling to discover new things. Besides that, I like to lie back, take in the scenery, and relax to enjoy life.