Readers Writers using semaphore

, by Engineer's Vision

// READERS WRITERS C - CODE TO BE PERFORMED IN LINUX
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#include<stdlib.h>


sem_t mutex,writerblock;
int data=0,readcount=0;



void * reader(void * arg)
{
    int f=(int)arg;
    printf("\n Reader %d",f);

    sem_wait(&mutex);
    readcount++;

    if(readcount==1)
        sem_wait(&writerblock);
    sem_post(&mutex);
    printf("Reader %d read the data %d",f,data);
    sem_wait(&mutex);

    readcount--;

    sleep(2);

    if(readcount==0)
        sem_post(&writerblock);
    sem_post(&mutex);
}


void * writer(void * arg)
{
    int f=(int)arg;
    sem_wait(&writerblock);
    data+=2;
   
    printf("\n Writer %d has written data %d",f,data);
    sleep(1);

    sem_post(&writerblock);
}


int main()
{
    int no,i;

    sem_init(&mutex,0,1);
    sem_init(&writerblock,0,1);

    printf("\nEnter no of readers and writers");
    scanf("%d",&no);
       
    pthread_t r[no],w[no];
   
    for(i=0;i<no;i++)
    {
        pthread_create(&r[i],NULL,reader,(void *)i);
        pthread_create(&w[i],NULL,writer,(void *)i);
    }

    for(i=0;i<no;i++)
    {
        pthread_join(r[i],NULL);
        pthread_join(w[i],NULL);
    }   
   
    sem_destroy(&mutex);
    sem_destroy(&writerblock);
}


0 comments: