We may not have the course you’re looking for. If you enquire or give us a call on +49 8000101090 and speak to our training experts, we may still be able to help with your training requirements.

The Gist
1. Semaphores are synchronisation mechanisms used to coordinate concurrent processes and threads.2. Binary semaphores have two states, while counting semaphores manage multiple available permits.3. Wait and signal operations must execute atomically to maintain correct synchronisation.4. Semaphores support resource management and task coordination but require careful implementation.5. Incorrect semaphore usage can lead to deadlocks, resource starvation and performance overhead.
Imagine a busy intersection where traffic lights keep everything running smoothly without a hint of chaos! In the world of Operating Systems (OS), semaphores play a similar role, orchestrating the flow of processes to oversee orderly access to shared resources by preventing collisions and deadlocks. This blog explores what is semaphore in OS, how they operate, how they are implemented, and more! Read on and learn why these tools are crucial for maintaining harmony in the digital landscape!
What is a Semaphore in an Operating System?
A semaphore is a synchronisation mechanism used in operating systems and concurrent programming to coordinate access to shared resources. It maintains an internal value representing available permits or a synchronisation state. Processes or threads interact with the semaphore through operations that acquire and release permits.
When a permit is available, a process or thread can acquire the permit and continue. If no permit is available, it must wait according to the semaphore's implementation. Semaphores are particularly useful when multiple processes or threads compete for shared resources such as memory buffers, database connections and hardware devices.
How Does a Semaphore Work?
A semaphore works by maintaining a value that changes when processes or threads acquire and release permits. A typical sequence involves the following activities:
a) Initialisation: The semaphore is created with an initial permit count.
b) Wait: A process attempts to acquire a permit.
c) Access: If a permit is available, the process proceeds with its activity.
d) Blocking: If no permit is available, the process waits.
e) Signal: A process releases a permit after completing its work.
f) Continuation: A waiting process may then acquire an available permit and proceed.
When to Utilise a Semaphore?
A semaphore is a powerful synchronisation tool used in programming to control access to shared resources in a concurrent or multi-threaded environment. Here are some scenarios where you should consider using a semaphore:
a) Limiting Access to a Resource: When you have a resource, like a database connection or a file, that can only handle a limited number of users at the same time, a semaphore can be used to ensure that only a specific number of threads or processes can access the resource concurrently.
b) Coordination Between Threads: If you need to coordinate tasks between multiple threads, such as ensuring that one task is completed before another begins, semaphores can help manage this flow. For instance, you might use a semaphore to make sure that a producer thread does not overwhelm a consumer thread.
c) Resource Pool Management: When dealing with a pool of resources, such as a thread pool, a semaphore can track how many resources are available and block threads when all resources are in use. As threads release resources back into the pool, the semaphore count increases, allowing other waiting threads to proceed.
d) Rate Limiting: There are situations where you need to limit the rate at which requests or operations are performed (e.g., API requests or network connections). It these situations, semaphores can be used to restrict the number of operations executed over a certain period.
Real-world Example: Managing Database Connections
Imagine an application with only three database connections available. A counting semaphore initialised with three permits helps coordinate access.
1. Process P1: Acquires the first permit.2. Process P2: Acquires the second permit.3. Process P3: Acquires the final permit.4. Process P4: Waits because no permits remain.5. When P1 Finishes: It releases its permit, allowing a waiting process such as P4 to acquire access.
Different Types of Semaphores
Now that the basic concept behind Semaphores has been established, let’s move on to different types of Semaphores. Semaphores are primarily divided into two categories, namely binary and counting semaphores, each with distinct roles in process synchronisation and resource management. We explore these two categories below:
1) Binary Semaphore
A binary semaphore, a binary (0 or 1) flag, plays a crucial role in ensuring mutual exclusion. When used as the mutual exclusion mechanism, it guarantees that only the allocated resources will be affected.
A binary semaphore has two values: 0 and 1. Initially set to 1, it becomes 0 when process P1 enters the critical section. If another process P2 tries to enter, it must wait until P1 exits and signals, which resets the semaphore to 1. This ensures mutual exclusion, allowing only one process to enter the critical section at a time. Here’s an illustration:
2) Counting Semaphore
Unlike a binary semaphore, which can only have values of 0 or 1, a counting semaphore can have a range of values, allowing it to control access for multiple entities simultaneously. Conceptually, a semaphore is a non-negative integer. Its value, initialised to the number of free resources, automatically increases when a resource is added and decreases when a resource is deleted, ensuring dynamic resource management.
When a resource has three instances, the semaphore is initialised to 3 (i.e. S = 3). Each process accessing the resource calls the wait function, decrementing the semaphore. Up to three processes can access the resource simultaneously. A fourth process must wait until a current process exits and signals, increasing the semaphore by 1.
Looking to master the craft of responsive web design? Sign up for our Front-End Web Development Course now!
Semaphore Operations
Semaphores use two fundamental operations called wait and signal. These operations coordinate access to shared resources by changing the availability of semaphore permits. They must be performed atomically to prevent multiple processes or threads from interfering with one another.
1) Wait Operation
The wait operation, also called P() or down(), attempts to acquire a semaphore permit. If a permit is available, the operation acquires it and allows the process to continue. If no permit is available, the process waits until a permit becomes available. The exact waiting mechanism depends on the implementation.
Conceptual pseudocode:
wait(S):atomically:if S has an available permit:acquire one permitreturnotherwise:block until a permit can be acquired
The availability check and permit acquisition are part of one atomic synchronisation operation.
2) Signal Operation
The signal operation, also called V() or up(), releases a semaphore permit. It updates the semaphore's available permit count or enables a waiting process or thread to proceed, depending on the implementation.
Conceptual pseudocode:
signal(S):atomically:release one permitif a process is waiting:make an eligible waiting process runnable
The signal operation helps coordinate resource availability, but it does not guarantee which waiting process will run next.
How to Implement a Semaphore?
An implementation with no busy waiting needs an integer value (to hold semaphore value) and a pointer to the subsequent process in the waiting list. The list consists of processes put to sleep on the wait for operation. To command the processes, the kernel uses two additional operations, block and wakeup.
Semaphore implementation is a critical section problem since we don’t want more than one process to access the semaphore variable concurrently. Several programming languages support concurrency and semaphores. Java, for example, supports semaphores, which we can use in our multi-threaded programs.
Example of Implementing a Semaphore in C:
This example uses a binary semaphore to make sure that only one thread can access a shared resource at a time.

How It Works:
a) sem_init(): Initialises the semaphore with one available permit.
b) sem_wait(): Acquires the permit before accessing the shared resource.
c) sem_post(): Releases the permit, allowing another waiting thread to proceed.
d) sem_destroy(): Cleans up the semaphore after both threads finish.
Explore the fundamentals of web development with our detailed, up-to-date Web Development Training - Sign up now!
The Benefits of Using Semaphores Include
1) Effective Process Synchronisation: Semaphores make process synchronisation dependable, guaranteeing that numerous processes interact with shared resources in a planned and controlled way. This maintains a strategic distance from racial predispositions and information disparities, which could deliver off-base outcomes.
2) Flexible Resource Management: Semaphores empower you with flexible access control for shared resources. They are valuable for many uses where asset portion prerequisites change since they can be adapted to oversee different levels of asset accessibility, giving you control over resource management.
3) Simple and Frequently Used: Semaphores offer a comparatively simple synchronisation technique in concurrent programming and operating systems. They are generally helpful because they are easy to implement and effective.
Drawbacks of Using Semaphores
Despite its benefits, semaphores can pose challenges as well. Here are some drawbacks:
1) Difficult Implementation: Using semaphores can be troublesome and error-prone. Execution errors can cause synchronisation issues and thus make the investigation and debugging difficult.
2) Potential Deadlock and Livelock: Incorrect synchronisation can cause semaphores to unintentionally cause deadlock and livelock scenarios, in which processes become locked into an unrecoverable state. These situations occur when clashes over assets keep processes from pushing ahead.
3) Synchronisation Overhead: Semaphores can cause synchronisation overhead, impacting system performance if used excessively. Semaphores must be acquired and released periodically to avoid context switching and delays that hinder system performance.
Semaphore Safety Checklist
Use this checklist when implementing semaphore-based synchronisation
□ Initialise the semaphore with the correct permit count.□ Pair every successful acquisition with the appropriate release.□ Avoid releasing more permits than intended.□ Use a consistent acquisition order when working with multiple synchronisation objects.□ Do not assume semaphores automatically prevent deadlocks.□ Protect shared data with appropriate synchronisation.□ Handle acquisition failures, interruptions, and cleanup correctly.
Lily Turner transforms complex data concepts into structured resources for aspiring and established data professionals. Her writing demonstrates how analytical methods and emerging technologies can be used to investigate problems, generate insights and support informed decisions.
View Detail