Mamoona Arshad

Mamoona Arshad

  • NA
  • 1
  • 922

readwrite lock

Jun 9 2015 3:49 AM
aoa sir,
Class ReaderWriterLock {
Semaphore mutex = 1; // declaration of a semaphore
OkToRead = 0; // a flag to check it is OK to read the database
OkToWrite = 0; // a flag to check it it is OK to write the database
int ACTIVEREADERS=0;// number of readers holding the read lock and accessing the database
WAITINGREADERS=0; // number of readers waiting to acquire read lock
ACTIVEWRITERS=0; // number of writers that have acquired write lock
// (practically this will always be 1)
WAITINGWRITERS=0; // number of writers that are waiting for write lock
void AcquireReadLock()
{
P(mutex); // remember that P operation on a semaphore means decrementing its value
if ((ACTIVEWRITERS == 0)
{
V(OkToRead); // remember that V operation on a semaphore means incrementing its value ACTIVEREADERS++;
}
else
{
WAITINGREADERS++;
}
V(mutex);
P(OkToRead);
}
void ReleaseReadLock()
{
P(mutex);
ACTIVEREADERS--;
if ((ACTIVEREADERS == 0) && (WAITINGWRITERS > 0))
{
V(OkToWrite);
ACTIVEWRITERS++;
WAITINGWRITERS--;
}
V(mutex);
}
void AcquireWriteLock()
{
P(mutex);
if (ACTIVEWRITERS + ACTIVEREADERS == 0)
{
V(OkToWrite);
ACTIVEWRITERS++;
}
else
{
WAITINGWRITERS++;
}
V(mutex);
P(OkToWrite);
}
void ReleaseWriteLock()
{
P(mutex);
ACTIVEWRITERS--;
if (WAITINGWRITERS > 0)
{
V(OkToWrite);
ACTIVEWRITERS++;
WAITINGWRITERS--;
}
else
{
while (WAITINGREADERS > 0)
{
V(OkToRead);
ACTIVEREADERS++;
WAITINGREADERS--;
}
}
V(mutex);
}
} // end of class
this is s code sir can you tell me it is either writer preference code or reader priority  code. and kindly suggest me starvation free code.