Last active
December 4, 2018 06:12
-
-
Save mirsahib/c1442ecaf2a07e3636b802f0f9d850eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<pthread.h> | |
#include<stdio.h> | |
#include<stdlib.h> | |
pthread_mutex_t x,wsem; | |
pthread_t tid; | |
int readcount; | |
void intialize() | |
{ | |
pthread_mutex_init(&x,NULL); | |
pthread_mutex_init(&wsem,NULL); | |
readcount=0; | |
} | |
void * reader (void * param) | |
{ | |
int waittime; | |
waittime = rand() % 5; | |
printf("\nReader is trying to enter"); | |
pthread_mutex_lock(&x); | |
readcount++; | |
if(readcount==1) | |
pthread_mutex_lock(&wsem); | |
printf("\n%d Reader is inside ",readcount); | |
pthread_mutex_unlock(&x); | |
sleep(waittime); | |
pthread_mutex_lock(&x); | |
readcount--; | |
if(readcount==0) | |
pthread_mutex_unlock(&wsem); | |
pthread_mutex_unlock(&x); | |
printf("\nReader is Leaving"); | |
} | |
void * writer (void * param) | |
{ | |
int waittime; | |
waittime=rand() % 3; | |
printf("\nWriter is trying to enter"); | |
pthread_mutex_lock(&wsem); | |
printf("\nWrite has entered"); | |
sleep(waittime); | |
pthread_mutex_unlock(&wsem); | |
printf("\nWriter is leaving"); | |
sleep(30); | |
exit(0); | |
} | |
int main() | |
{ | |
int n1,n2,i; | |
printf("\nEnter the no of readers: "); | |
scanf("%d",&n1); | |
printf("\nEnter the no of writers: "); | |
scanf("%d",&n2); | |
for(i=0;i<n1;i++) | |
pthread_create(&tid,NULL,reader,NULL); | |
//why we are not using this 'pthread(&tid[i],NULL,reader,NULL)' | |
for(i=0;i<n2;i++) | |
pthread_create(&tid,NULL,writer,NULL); | |
//why we are not using this piece of code to terminate the thread | |
//for(int i=0;i<reader;i++) | |
// pthread_join(tid[i],NULL) | |
//same thing goes to writer thread | |
sleep(30); | |
exit(0); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment