read this....
Semaphore is quiet easy and simple...
Lets take an example from our real life which makes semaphore a simple task for me....
when
we are using a printer on lan network and ten's of computer are
connected to the same printer for printout so if anyone wants to get a
printout he can give a command and get that but suppose there is a
situation in which all the computers execute print command at the same
time so how will printer control it so there need to be some protocol
implementation to control the sequence otherwise what will happen if
printer will access all the commands at the same time imagine yourself,
It might be possible that all the picture get on the one paper. so we
use some technique to control it. in this example critical condition is
when computers are trying to access the printer. So there should be some
condition before entering the critical region so that a single process
will enter at one time and rest will be in the waiting condition till
one is accessing so we implement the semaphore.
While implementing one need to have knowledge of three system calls:
semget(); //it is used to declare semaphore
semctl(); //it is used to initialize semaphore
semop(); // it is used to control condition before entering and leaving the semaphore
so
now you need to think where to use what????... so we will implement
according to its use as such if semget is for declaration so we need to
declare it once and where you want to use semaphore.and also it returns
sem_id that is generated by kernel which is required to access the semop
command and for using semaphore in future.
and when it comes to
semctl() it is used for initializing the semaphore and it will make the
clients to see the condition and enter the semaphore so you need to
enter it once at time of deceleration but it is not mandatory it may
vary according to once need.
and semop() is used to decrease the
operator value before executing statement after entering critical region
and increment operator value again before leaning the critical region
so that other can access it....
see figure it will also help you to understand.
It looks like you're new here. If you want to get involved, click one of these buttons!