Reader writer problem solved using semaphore

Reader writer problem solved using semaphore

Readers/Writers Problem

• An object is shared among may threads, each belonging to one of two classes:

Readers: read data, never modify it

Writers: read data and modify it

• Using a single lock on the data object is overly restrictive => Want many readers reading the object at once

– Allow only one writer at any point

Correctness criteria:

– Each read or write of the shared data must happen within a critical section.

– Guarantee mutual exclusion for writers

.– Allow multiple readers to execute in the critical section at once

Reader Writer Problem Solution-
void * reader(void *) ;  
void *writer (void *) ;  
sem_t wsem,mutex ;  
int readcount=0 ;  
  int a=1,b=1;  
  sem_init(&wsem,0,1) ;  
  sem_init(&mutex,0,1) ;  
  pthread_t r,w,r1,w1 ;  
  pthread_create(&r,NULL,reader,(void *)a);  
  pthread_create(&w1,NULL,writer,(void *)b);  
  pthread_create(&r1,NULL,reader,(void *)a);  
  pthread_create(&w,NULL,writer,(void *)b);  
  pthread_join(w,NULL) ;  
  printf(“main terminated\n”);  
void * reader(void * arg)  
  int c=(int)arg ;  
  printf(“\nreader %d is created”,c);  
  sem_wait(&mutex) ;  
         sem_wait(&wsem) ;  
  sem_post(&mutex) ;  
/*Critcal Section */  
  printf(“\n\nreader %d is reading\n “,c);  
  sleep(1) ;  
  printf(“\nreader%d finished reading\n”,c);  
/* critical section completd */  
  sem_wait(&mutex) ;  
     readcount ;  
         sem_post(&wsem) ;  
  sem_post(&mutex) ;  
void * writer(void * arg)  
  int c=(int)arg ;  
  printf(“\nwriter %d is created”,c);  
  sem_wait(&wsem) ;  
  printf(“\nwriter %d is writing\n”,c) ;  
  printf(“\nwriter%d finished writing\n”,c);  
  sem_post(&wsem) ;  

Resolving technical problems:

Solve your technical problems instantly

We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM

Mail your problem details at [email protected] along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.