The Second Readerwriter problem requires that once a writer

The Second Reader-writer problem requires that, once a writer process is ready, it perform its write as soon as possible. That is, if a writer is waiting to access the object, no new readers can start reading. Write a semaphore-based solution for Second reader-writer problem.

Solution

#include<stdio.h>
#include<omp.h>

main()
{
int semaphore=0;
#pragma omp parallel num_threads(2) // two thread are created;
{
int i;
int tid=omp_get_thread_num();
do
{
printf(\"\ thread %d\ %d.read\ %d.write\ 5.exit\",tid,tid*2,tid*2+1);

//0: read at thread0 ;
//1: write at thread 0;
// 2: read at thread 1;
//3: write at thread 1;
//5: exit thread .;
scanf(\"%d\",&i);

switch(i)
{
case 0: if(semaphore==1)//thread 1 is writing;
{
while(semaphore==1)//wait untill semaphore becomes 0;
{
printf(\"\ shared data is in use\");
sleep(1);
}
}


printf(\"\ reading in thread 0\");
sleep(5);
printf(\"\ reading done in thread 0\");
break;

case 1: if(semaphore==1)// thread 1 is writing

{
while(semaphore==1)// wait until smaphore become 0
sleep(1);
}

semaphore=1;
printf(\"\ writing in thread 0\");
sleep(5);
printf(\"\ writing done in thread 0\");
semaphore=0;
break;


case 2: if(semaphore==1)//thread 0 is writing
{
while(semaphore==1)//wait untill semaphore becomes 0
{
printf(\"\ shared data is in use\");
sleep(1);
}
}

printf(\"\ reading in thread 1\");
sleep(5);
printf(\"reading done in thread 1\");
break;


case 3: if(semaphore==1)//thread 0 is writing
{
while(semaphore==1)//wait untill semaphore becomes 0
{
printf(\"\ shared data is in use\");
sleep(1);
}
}
semaphore=1;

printf(\"\ writing in thread 1\");
sleep(5);
printf(\"writing done in thread 1\");
semaphore=0;

break;
}
}
while(i<5);
}
}

======================================================================

run like this

akshay@akshay-Inspiron-3537:~/Chegg$ gcc readwrite.c -fopenmp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out

Comment about work because this code was my assignment last year.

The Second Reader-writer problem requires that, once a writer process is ready, it perform its write as soon as possible. That is, if a writer is waiting to acc
The Second Reader-writer problem requires that, once a writer process is ready, it perform its write as soon as possible. That is, if a writer is waiting to acc

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site