ANP 5. IPC Semaphore
ANP 5. IPC Semaphore
Semaphore
• A semaphore is a primitive for synchronization
between various
Inter-process Communication – Processes or
(IPC): POSIX Semaphore – Threads
• Location of semaphore
Harshad B. Prajapati – Posix named semaphore: Identified by Posix IPC names.
Associate Professor Used for synchronization of processes and threads.
Information Technology Department, – Memory based semaphores: in shared memory. Used for
Dharmsinh Desai University, Nadiad synchronization of processes and threads.
Semaphore Semaphore
• Semaphore types • Operations on semaphore
– Binary : can assume value 1 or 0
– Create a semaphore
• Used for mutual exclusive access
• The caller specifies initial value. (Generally, 1, but can
– Counting: can assume unrestricted integer values.
be 0)
• Used to keep track of the number of entities (e.g. resources,
resource consumers, resource producers) – Wait for semaphore
• Test the value of semaphore
– Wait if value is less than or equal to 0, Otherwise decrement
the value by one.
– Post to semaphore
• Increment the value of semaphore. If there are waiting
processes, one of those is awakened.
Producer-Consumer using
Semaphore
Semaphore
• Binary semaphore can be used to achieve • Use two semaphores
mutual exclusion. (What about using mutex) – put = 1, (Can assume 1 means free)
• Semaphore v/s mutex – get = 0, (Can assume 0 means locked)
– A mutex must always be unlocked by the thread • Producer Consumer
that locked the mutex. for(;;){
– A semaphore post need not be performed by the sem_wait(&put); sem_wait(&get);
thread that did the semaphore wait. put data into buffer process data in buffer
– A semaphore has state associated with it (Count). sem_post(&get); sem_post(&put);
In condition variable, if no thread is waiting for }
condition, a signal gets lost. • If the consumer starts first, it will block.
1
7/21/2017
2
7/21/2017
3
7/21/2017
Semaphore limits
• SEM_NSEMS_MAX: the maximum number of
semaphores that a process can have open at
once (at least 256).
• SEM_VALUE_MAX: the maximum value of the
semaphore (at least 32767)