In: Computer Science
This is standard reader writer problem.for reference , I am attaching below image.
===========================================================================
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
sem_t mutex,writeblock; // These will be used to check if there is mutual exclusion between blocks
int data = 0,rcount = 0; //Data will be written by writer and rcount will store reader’s count
int sleepLength = 2; // used to represent work
void *reader(void *arg)
{
int f;
f = ((int)arg);
sem_wait(&mutex); // it will put wait condition on reader
rcount = rcount + 1; //increment reader count
if(rcount==1) //allows only one reader at time
sem_wait(&writeblock); //if reader is 1.meaning reader is writing then no one can write so it puts wait
sem_post(&mutex); //send signal to reader ..now ready to read
printf("Data read by the reader%d is %d\n",f,data); //shows current reader and data
sleep(sleepLength); // 1 second of "work" is being done here
sem_wait(&mutex);// it will put wait condition on reader
rcount = rcount - 1; //and it will reduce count and make it free
if(rcount==0) //Now no one is reading,then writer can write
sem_post(&writeblock); //signal writer for writing
sem_post(&mutex);// After all this,again reader can write,so it sends signal
}
void *writer(void *arg)
{
int f;
f = ((int) arg);
sem_wait(&writeblock); // It will stop all writer
data++; //increases data by 1 which will be written
printf("Data writen by the writer%d is %d\n",f,data); //shows current writer and data
sleep(sleepLength); // 1 second of "work" is being done here
sem_post(&writeblock);// It will send signal and makes value 1,so that other writers can write
}
int main()
{
int i,b;
pthread_t rtid[5],wtid[5]; // 5 threads are created
sem_init(&mutex,0,1);// 0 means it is shared across threads and 1 means it is initial value
sem_init(&writeblock,0,1); means it is shared across threads and 1 means it is initial value
for(i=1;i<=5;i++)//loop to create writers and readers
{
pthread_create(&wtid[i],NULL,writer,(void *)i);
pthread_create(&rtid[i],NULL,reader,(void *)i);
//printf("looping in for\n");
}
//All thread will be joined after execution
for(i=1;i<=5;i++)//loop for
{
pthread_join(wtid[i],NULL);
pthread_join(rtid[i],NULL);
}
return 0;//resetting
}