NOTE MAKE SURE DO IT RIGHT WAY THE CODE I WANT CORRECT CODE FOR THIS QUESTION 9.
ID: 3877554 • Letter: N
Question
NOTE MAKE SURE DO IT RIGHT WAY THE CODE I WANT CORRECT CODE FOR THIS QUESTION
9. Consider the situation in which many threads must access the same shared memory a some reading and some writing, with the natural constraint that no process may access memory for reading or writing while another process is in the act of writing to it. It is more readers readers! Write code for both your Reader() and Writer) threads t one time, the shared allowed for two or to access the share at the same time. Be careful your writer should NOT starve a C solution using pthreads for this synchronization problem. Be sure to provideExplanation / Answer
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t readCountAccess;
sem_t databaseAccess;
int rc=0;
void *Readerfun(void *argu);
void *Writerfun(void *argu);
int main()
{
int i=0,ReaderThreadNumber=0,WriterThreadNumber;
sem_init(&readCountAccess,0,1);
sem_init(&databaseAccess,0,1);
pthread_t Readers_thr[100],Writer_thr[100];
printf(“ Provide Readers thread numbers(MAX 10)”);
scanf(“%d”,&ReaderThreadNumber);
printf(“ Provide Writers thread number(MAX 10)”);
scanf(“%d”,&WriterThreadNumber);
for(i=0;i<readerthreadnumber;i++)
{
pthread_create(&Readers_thr[i],NULL,Reader,(void *)i);
}
for(i=0;i<writerthreadnumber;i++)
{
pthread_create(&Writer_thr[i],NULL,Writer,(void *)i);
}
for(i=0;i<WriterThreadNumber;i++)
{
pthread_join(Writer_thr[i],NULL);
}
for(i=0;i<ReaderThreadNumber;i++)
{
pthread_join(Readers_thr[i],NULL);
}
sem_destroy(&databaseAccess);
sem_destroy(&readCountAccess);
return 0;
}
void * Writerfun(void *argu)
{
sleep(1);
int temprory=(int)argu;
printf(“ Writer %d is trying to access into db for alter the data”,temprory);
sem_wait(&databaseAccess);
printf(“ Writer %d is writting into the db”,temprory);
printf(“ Writer %d is left the db”);
sem_post(&databaseAccess);
}
void *Readerfun(void *args)
{
sleep(1);
int temprory=(int)argu;
printf(“ Reader %d is trying to access into the Db for reading the data”,temprory);
sem_wait(&readCountAccess);
rc++;
if(rc==1)
{
sem_wait(&databaseAccess);
printf(“ Reader %d is reading the db”,temprory);
}
sem_post(&readCountAccess);
sem_wait(&readCountAccess);
rc–;
if(rc==0)
{
printf(“ Reader %d is left the db”,temprory);
sem_post(&databaseAccess);
}
sem_post(&readCountAccess);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.