Readers Writers Problem using Semaphores
Reader Priority problem
Readers Writers problem in operating system for solving synchronization problem can be solved. This program is for unix machine as their only you can run this code. This program demonstrate reader priority code for reader writer problem.
- Problem statement for implement Readers Writers problem using semaphores with reader priority using C language. Use mutex and semaphores to implement above problem in c language environment.
In reader priority case, reader will always be given priority to other processes. Writer has to wait every time if their is any read request to be completed. So by this simulation of readers writers problem we can see how actually this problem can be tackled in real time.
Readers Writers Problem Code
1 |
#include <br/> #include <br/> #include <br/> void * reader(void *) ; <br/> void *writer (void *) ; <br/> sem_t wsem,mutex ; <br/> int readcount=0 ; <br/> main() <br/> { <br/> int a=1,b=1; <br/> system("clear"); <br/> sem_init(&wsem,0,1) ; <br/> sem_init(&mutex,0,1) ; <br/> pthread_t r,w,r1,w1 ; <br/> pthread_create(&r,NULL,reader,(void *)a); <br/> a++; <br/> pthread_create(&w1,NULL,writer,(void *)b); <br/> b++; <br/> pthread_create(&r1,NULL,reader,(void *)a); <br/> pthread_create(&w,NULL,writer,(void *)b); <br/> pthread_join(r,NULL); <br/> pthread_join(w1,NULL); <br/> pthread_join(r1,NULL); <br/> pthread_join(w,NULL) ; <br/> printf("main terminated\n"); <br/> } <br/> void * reader(void * arg) <br/> { <br/> int c=(int)arg ; <br/> printf("\nreader %d is created",c); <br/> sleep(1); <br/> sem_wait(&mutex) ; <br/> readcount++; <br/> if(readcount==1) <br/> sem_wait(&wsem) ; <br/> sem_post(&mutex) ; <br/> /*Critcal Section */ <br/> printf("\n\nreader %d is reading\n ",c); <br/> sleep(1) ; <br/> printf("\nreader%d finished reading\n",c); <br/> /* critical section completd */ <br/> sem_wait(&mutex) ; <br/> readcount-- ; <br/> if(readcount==0) <br/> sem_post(&wsem) ; <br/> sem_post(&mutex) ; <br/> } <br/> void * writer(void * arg) <br/> { <br/> int c=(int)arg ; <br/> printf("\nwriter %d is created",c); <br/> sleep(1); <br/> sem_wait(&wsem) ; <br/> printf("\nwriter %d is writing\n",c) ; <br/> sleep(1); <br/> printf("\nwriter%d finished writing\n",c); <br/> sem_post(&wsem) ; <br/> } |
Source projectgeek.com