Small and simple
#include<stdio.h>
#include<semaphore.h>
sem_t x,wsem;
int rc;
int data;
void* reader(void *p)
{
int *i=(int*)p;
while(1)
{
sem_wait(&x);
rc++;
if(rc==1)
sem_wait(&wsem);
sem_post(&x);
printf("Reader %d Data= %d\n",*i,data);
sem_wait(&x);
rc--;
if(rc==0)
sem_post(&wsem);
sem_post(&x);
sleep(2);
}
}
void* writer(void *p)
{
while(1)
{
sem_wait(&wsem);
data=random()%100;
printf("Writer wrote data= %d\n",data);
sem_post(&wsem);
sleep(2);
}
}
int main()
{
int i;
pthread_t readerTh[4],writerTh;
int p[]={1,2,3,4};
sem_init(&x,0,1);
sem_init(&wsem,0,1);
for(i=0;i<4;i++)
pthread_create(&readerTh[i],NULL,reader,(void*)&p[i]);
pthread_create(&writerTh,NULL,writer,NULL);
pthread_join(writerTh,NULL);
return;
}
#include<stdio.h>
#include<semaphore.h>
sem_t x,wsem;
int rc;
int data;
void* reader(void *p)
{
int *i=(int*)p;
while(1)
{
sem_wait(&x);
rc++;
if(rc==1)
sem_wait(&wsem);
sem_post(&x);
printf("Reader %d Data= %d\n",*i,data);
sem_wait(&x);
rc--;
if(rc==0)
sem_post(&wsem);
sem_post(&x);
sleep(2);
}
}
void* writer(void *p)
{
while(1)
{
sem_wait(&wsem);
data=random()%100;
printf("Writer wrote data= %d\n",data);
sem_post(&wsem);
sleep(2);
}
}
int main()
{
int i;
pthread_t readerTh[4],writerTh;
int p[]={1,2,3,4};
sem_init(&x,0,1);
sem_init(&wsem,0,1);
for(i=0;i<4;i++)
pthread_create(&readerTh[i],NULL,reader,(void*)&p[i]);
pthread_create(&writerTh,NULL,writer,NULL);
pthread_join(writerTh,NULL);
return;
}
No comments:
Post a Comment