-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproconsumer.c
70 lines (70 loc) · 2.11 KB
/
proconsumer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//Implementation of producer-consumer problem//
//Alin Babu.7,R5//
//File name : proconsumer.c//
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#include<stdlib.h>
#define buffersize 10
pthread_mutex_t mutex; //Intiallize declaration//
pthread_t tidP[20],tidC[20]; //Thread declaration for producer and consumer//
sem_t full,empty; //Semapore declaration//
int counter;
int buffer[buffersize]; //Buffer declaration//
void initialize() //Funstion to initiallizw mutex and semaphore//
{
pthread_mutex_init(&mutex,NULL);
sem_init(&full,1,0);
sem_init(&empty,1,buffersize);
counter=0;
}
void write(int item) //Function to write into the buffer//
{
buffer[counter++]=item;
}
int read() //Function to read from buffer//
{
return(buffer[--counter]);
}
void * producer (void * param) //Function for producer thread to wait and write item to buffer//
{
int waittime,item,i;
item=rand()%5;
waittime=rand()%5;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
printf("\nProducer has produced item: %d\n",item);
write(item);
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
void * consumer (void * param) //Function for consumer thread to wait and read item to buffer//
{
int waittime,item;
waittime=rand()%5;
sem_wait(&full);
pthread_mutex_lock(&mutex);
item=read();
printf("\nConsumer has consumed item: %d\n",item);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
int main()
{
int n1,n2,i;
initialize();
printf("\nEnter the no of producers:");
scanf("%d",&n1);
printf("\nEnter the no of consumers:");
scanf("%d",&n2);
for(i=0;i<n1;i++)
pthread_create(&tidP[i],NULL,producer,NULL);
for(i=0;i<n2;i++)
pthread_create(&tidC[i],NULL,consumer,NULL);
for(i=0;i<n1;i++)
pthread_join(tidP[i],NULL);
for(i=0;i<n2;i++)
pthread_join(tidC[i],NULL);
//sleep(5);
exit(0);
}