#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
sem_t prodlock;
sem_t conslock;
int product;
void *producer()
{
int i=1;
int item=1;
while(i<=5)
{
sem_wait(&prodlock);
product=item;
printf("\nProduced:%d",product);
sem_post(&conslock);
item++;
i++;
}
}
void *consumer()
{
int i=1;
while(i<=5)
{
sem_wait(&conslock);
printf("\nConsumed:%d",product);
sem_post(&prodlock);
i++;
}
}
void main()
{
pthread_t pid;
pthread_t cid;
pthread_attr_t *attr=NULL;
sem_init(&prodlock,0,1);
sem_init(&conslock,0,0);
if(pthread_create(&pid,attr,producer,NULL)!=0)
{
printf("\nError in creating Producer thread");
}
if(pthread_create(&cid,attr,consumer,NULL)!=0)
{
printf("\nError in creating Consumer thread");
}
pthread_join(pid,NULL);
pthread_join(cid,NULL);
}
OUTPUT:
Produced:1
Consumed:1
Produced:2
Consumed:2
Produced:3
Consumed:3
Produced:4
Consumed:4
Produced:5
Consumed:5
#include<semaphore.h>
#include<pthread.h>
sem_t prodlock;
sem_t conslock;
int product;
void *producer()
{
int i=1;
int item=1;
while(i<=5)
{
sem_wait(&prodlock);
product=item;
printf("\nProduced:%d",product);
sem_post(&conslock);
item++;
i++;
}
}
void *consumer()
{
int i=1;
while(i<=5)
{
sem_wait(&conslock);
printf("\nConsumed:%d",product);
sem_post(&prodlock);
i++;
}
}
void main()
{
pthread_t pid;
pthread_t cid;
pthread_attr_t *attr=NULL;
sem_init(&prodlock,0,1);
sem_init(&conslock,0,0);
if(pthread_create(&pid,attr,producer,NULL)!=0)
{
printf("\nError in creating Producer thread");
}
if(pthread_create(&cid,attr,consumer,NULL)!=0)
{
printf("\nError in creating Consumer thread");
}
pthread_join(pid,NULL);
pthread_join(cid,NULL);
}
OUTPUT:
Produced:1
Consumed:1
Produced:2
Consumed:2
Produced:3
Consumed:3
Produced:4
Consumed:4
Produced:5
Consumed:5
No comments:
Post a Comment