What is aSemaphore?
• A semaphore is a synchronization mechanism used in computing to
manage concurrent processes or threads in a system, ensuring they
do not conflict when accessing shared resources.
• It operates as a counter that can be incremented or decremented,
representing the availability of a resource.
• A semaphore is an integer variable that represents the count of
available resources or the permission to proceed.
• It can be manipulated only through two atomic operations: wait (P
operation) and signal (V operation).
3.
How semaphore works?
•Wait (P): Decrements the semaphore’s value. If the value becomes
negative, the process is blocked and placed in a queue.
• Signal (V): Increments the semaphore’s value and wakes up a waiting
process if any exist.
wait(S);
semaphore S =1;
critical_section();
// Decrement semaphore.
Block if S <= 0.
signal(S);
// Execute critical
operations
// Increment semaphore.
Unblock waiting process if any.
// Initialize semaphore
8.
Types of Semaphores
•Binary Semaphore:
• Functions as a simple lock with two states (0 or 1).
• It's often used for managing exclusive access to a single resource.
• Counting Semaphore:
• Can have a value greater than 1, used to manage access to multiple instances
of a resource.
9.
Uses of Semaphores
•Mutual Exclusion: Semaphore ensures that only one process accesses
a shared resource at a time.
• Process Synchronization: Semaphore coordinates the execution order
of multiple processes.
• Resource Management: Limits access to a finite set of resources, like
printers, devices, etc
• Reader-Writer Problem: Allows multiple readers but restricts the
writers until no reader is present.
• Avoiding Deadlocks: Prevents deadlocks by controlling the order of
allocation of resources.