Wednesday, November 2, 2011

Semaphore and Mutexes

so what are the methods to implement mutexes ?

various, it depends how the system is
for uniprocessor
  • disabling the interrupts
for multiprocessor
  • use atomic operations like ExchangeWord or testAndSet if supported by processor bus
other wise
  • use the software solution
busy waiting is involved in case of option 2/3
option 2 requires hw assistance and can be employed if multiple processors share the memory as well
option 3 is generic and can be used if none of other solutions are working


So what is the option 3 ?

2 process mutex

int cur = -1;
int interested [2] ;
lock(int id)
{
cur = id;
interested[id] = true;
while(cur == id && interested[id ^1])
;
}

unlock(int id)
{
interested[id] = 0;
}

ok, what other problem may arise in multiprogramming?
in multiprogramming, while sharing of resources, process cooperate /compete
to deal with co-operation , mutex is employed, for competing processes in view of shared limited resources, we need to use the semaphores.
actually semaphores can be used to solve the problem of resource sharing as well as mutual exclusion.

So what is Semaphore ?
just an integer variable . Actually a data structure which mostly has integer and 2 operations P and V (wait and signal). Semaphore can be attached / detached to particular process to make them share the resources.

wait(int sem_id)
{
Semaphore *s = getSemaPhore(sem_id);
lock(s->lock);
if(s->busy == false)
{
s->busy = true;
}
else
{
s->q->enq(current_process);
block(current_process);
}
unlock(s->lock);
}

similarly
signal(int sem_id)
{ Semaphore *s = getSemaPhore(sem_id);
lock(s->lock);
if(!s->q->empty())
{
unBlock(s->q->deq() );
}
else
{
s->busy = false;

}
unlock(s->lock);

}

Readers writes problem?
  • no reader shall wait unless share is open for reading
  • as soon as writer starts , all reader should stop and exclusive access to writer should be provided. Writers should be preferred

No comments:

Post a Comment