Thursday, 25 April 2013

Semaphores

These are like integers but has the following three difference from them:
1) Its value can be initialized as integer but only increment or decrement operations are allowed and its current value can't be read.
2) If any thread decrements its value and result is negative then thread itself can't continue until any other thread increments the Semaphore.
3) If any thread increments Semaphore and their are another threads waiting ,one of the thread gets blocked which was in waiting list.


Explanation : Consider the example of a Cyber Cafe which has 20 cabins and is used by one person at a time for the prevention of dispute user requests a cabin from front counter to use PC.When user work is over he returns to counter makes payment and indicates that now one cabin is free.If no cabin is free than user has to wait until any cabin is free.


The person sitting at front counter only knows the no. of occupied cabins ant not the particular cabin which is occupied.if somebody leaves the cabin the no. of occupied cabin's no. is decremented and if somebody requests a cabin the no. of occupied cabin's incremented.

In this Example front desk is a Semaphore, Cabins are resources and Users or customers are Process.The Initial value of Semaphore is 20.whenever any user requests a PC and is granted the value of semaphore is decremented to 19.if next customer comes than to 18 and so on up to 0.Now next request can't be fulfilled until somebody leave the cabin and increments the semaphore value to 1.

Why Semaphores are used?
1) Semaphores help programmers to avoid errors
2)Solutions using Semaphores are clean and organized.
3)These can be implemented on many systems and are easily portable.



No comments:

Post a Comment