Operating System (CS2701)
semaphore
Dr. Rourab Paul
Computer Science Department, SNU University, Chennai
Operating System
Semaphore
Operating System
2
A semaphore is a synchronization mechanism used in operating systems and concurrent programming to control access to a shared resource by multiple threads or processes using simple integer value.
Semaphore
Operating System
3
Mutex = “I’m using this resource — wait until I’m done.”
Signal/Semaphore = “Hey, I’ve finished something — what you are saying
line is
busy
Semaphore
Operating System
4
Mutex = “I’m using this resource — wait until I’m done.”
Signal/Semaphore = “Hey, I’ve finished something — you can sta
bye
Definitions of wait and signal(post)
Operating System
5
wait(S) {
while (S <= 0)
; // busy
wait S--;
}
signal(S) {
S++;
}
All the modifications to the integer value of the semaphore in the wait() and signal() operation must be executed indivisibly. That is when one process modifies the semaphore value, no other process can simultaneously modify that same semaphore value
Counting vs Binary Semaphores
Operating System
6
Counting Semaphore
Binary Semaphore
named & unmanned semaphore
Operating System
7
Unnamed semaphore = a physical ticket box inside your office — only people already in your office can see and use it.�
Named semaphore = a public locker with a name/number in the building lobby — any process with the name can use it.
unnamed semaphore
Operating System
8
In the process’s memory (shared memory or global variable).
sem_t sem;
sem_init(&sem, 0, 1); // 0 = shared between threads, 1 = initial value
sem_wait(&sem); // acquire
sem_post(&sem); // release
sem_destroy(&sem);
named semaphore
Operating System
9
In the kernel, identified by a string name (like a file).
sem_t *sem = sem_open("/mysem", O_CREAT, 0644, 1);
sem_wait(sem); // acquire
sem_post(sem); // release
sem_close(sem);
sem_unlink("/mysem"); // remove name
Sample Programs
Operating System
10
Thank You
Operating System
11