Tuesday, February 23, 2010

SEMAPHORES IN OPERATING SYSTEMS

DEFINITION OF SEMAPHORES:

Semaphores are the protected variables or abstract data types that controls several processes trying to access same resources.

There are two types of semaphores available

1: Binary semaphore :

It is a simple true or false flag that controls access to a single resource.

2: Counting semaphores:

It is counter for the set of available resources.






HISTORY:

Semaphore concept was invented by the Dutch computer scientist Edsgar Dijkstra .



Important points to be Noted:

1: The UNIX command to give a list of existing semaphores is

ipcs -s

2: Semaphores co-ordinate access to a resource by different processes.

3: Semaphores are stored in kernel so that it can be accessed by all the processes.

4: Function that is used to create semaphores is semget()

This function takes three arguments as input:

a) Name of the semaphore.

b)Number of sub-semaphores to be created.

c)Semaphore mode. (read or rewrite)

Return integer value from this function indicates Semaphore id and if value is -1 error has occured in creation.

5: Semaphores are deleted by using the function semdelete.

6:Value of Semaphore represents Number of threads.



MUTEX :

A Mutex is a binary semaphore that usually incorporates extra features such as Ownership, priority inversion, protection etc.



Explanation of the Working :

Semaphores help in avoiding two or more processes to simultaneously access a common resource and attain deadlocks. So Basically semaphores prevent deadlocks.

When a process is accessing a resource of the system , it increments the Semaphore value which is stored in the kernel if it is a counting semaphore , else flag is set to true for binary Semaphore . When an another process tries to access the same resource it checks the Semaphore variable set for that particular address , if the flag is set to true the process waits for the earlier process to complete .Thus avoiding deadlocks among processes.

Semaphore analogy is similar to a restaurant say (some taj hotel) ,the tables being the resources available for the people( process ) to occupy.

Initially all the tables are empty as and when the people arrive they are provided tables for seating on the basis of their arrival or if they have reserved the table earlier. Similarly processes can be given priority for the available resources. As people start to occupy the tables the number of available tables get reduced and finally the tables are comletely occupied and people have to wait for their turn, which is controlled by the manager who acts as a semaphore. Thus when the tables become empty new people are given the access to the table based on the priority of their occurence. Similarly the processes have to wait till their turn for accessing the resources comes, which is controlled by the Semaphore.



Thus semaphores play a very important role in the smooth execution of the OS instructions.

No comments: