What is Semaphore in OS: Definition, Usage, and Example
semaphore in an operating system is a tool used to control access to shared resources by multiple processes or threads. It helps prevent conflicts by signaling when a resource is free or busy, ensuring safe and orderly use.How It Works
A semaphore acts like a traffic light for processes or threads that want to use a shared resource. Imagine a bathroom with a limited number of stalls. The semaphore keeps count of how many stalls are free. When someone enters, the count decreases; when they leave, it increases.
This counting helps avoid clashes, like two people trying to use the same stall at once. If the count is zero, new arrivals must wait until a stall becomes free. This way, semaphores manage access safely and efficiently.
Example
This example shows a simple semaphore controlling access to a shared resource by two threads. The semaphore starts with a count of 1, allowing only one thread to enter the critical section at a time.
import threading import time # Create a semaphore with initial count 1 sem = threading.Semaphore(1) def access_resource(name): print(f"{name} is waiting to access the resource.") sem.acquire() # Wait or enter if available print(f"{name} has entered the critical section.") time.sleep(2) # Simulate resource usage print(f"{name} is leaving the critical section.") sem.release() # Signal resource is free # Create two threads thread1 = threading.Thread(target=access_resource, args=("Thread 1",)) thread2 = threading.Thread(target=access_resource, args=("Thread 2",)) thread1.start() thread2.start() thread1.join() thread2.join()
When to Use
Use semaphores when multiple processes or threads need to share limited resources safely. They are essential in preventing problems like data corruption or crashes caused by simultaneous access.
Common real-world uses include managing access to printers, files, or database connections where only a few users can use the resource at once. Semaphores help coordinate these accesses smoothly.
Key Points
- A semaphore controls access to shared resources by multiple processes or threads.
- It uses a counter to track available resources.
- Processes wait if the resource is busy and proceed when it becomes free.
- Semaphores prevent conflicts and ensure safe resource sharing.