0% found this document useful (0 votes)
9 views2 pages

Procon

Uploaded by

vipuldangat103
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

Procon

Uploaded by

vipuldangat103
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>

#define Maxitems 5
#define Buffersize 5
sem_t empty;
sem_t full;
int in =0;
int out =0;
int buffer[Buffersize];
pthread_mutex_t mutex;

void* producer(void *);


void* consumer(void *);
int main()
{
pthread_t pro[5],con[5];
pthread_mutex_init(&mutex, NULL);
sem_init(&empty,0,Buffersize);
sem_init(&full,0,0);
int a[5]={1,2,3,4,5};

for(int i=0;i<5;i++)
{
pthread_create(&pro[i],NULL,(void*)producer,(void*)&a[i]);
pthread_create(&con[i],NULL,(void*)consumer,(void*)&a[i]);
}
for(int i=0;i<5;i++)
{
pthread_join(pro[i],NULL);
pthread_join(con[i],NULL);
}
pthread_mutex_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);

return 0;
}

void* producer(void *pno)


{
int item;
item = rand();
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[in]=item;
printf("Producer: %d, produces the item: %d, at %d \n",*((int
*)pno),buffer[in],in);

in= (in+1)%Buffersize;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}

void* consumer(void *cno)


{
int item;
sem_wait(&full);
pthread_mutex_lock(&mutex);
item=buffer[out];
printf("Consumer: %d, removes the item: %d from %d \
n",*((int*)cno),buffer[out],out);
out=(out+1)%Buffersize;
pthread_mutex_unlock(&mutex);
}

You might also like