-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProducerConsumerSemaphore.c
74 lines (63 loc) · 1.54 KB
/
ProducerConsumerSemaphore.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
71
72
73
74
//This code is contributed by Sourajita Dewasi
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <stdio.h>
#define MaxItems 3
#define Shelf 3
sem_t empty;
sem_t full;
int sin = 0;
int sout = 0;
int buffer[Shelf];
pthread_mutex_t mutex;
void *Producer(void *P)
{
int item=1;
for(int i = 0; i < 3; i++) {
item = item+1;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[sin] = item;
printf("Produced Item %d at %d\n", buffer[sin],sin);
sin = (sin+1)%Shelf;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *Consumer(void *C)
{
for(int i = 0; i < 3; i++) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
int item = buffer[sout];
printf("Consumed Item %d from %d\n",item, sout);
sout = (sout+1)%Shelf;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int main()
{
pthread_t pro[3],con[3];
pthread_mutex_init(&mutex, NULL);
sem_init(&empty,0,3);
sem_init(&full,0,0);
int a[3] = {0,1,2};
for(int i = 0; i < 3; i++) {
pthread_create(&pro[i], NULL, (void *)Producer, (void *)&a[i]);
}
for(int i = 0; i < 3; i++) {
pthread_create(&con[i], NULL, (void *)Consumer, (void *)&a[i]);
}
for(int i = 0; i < 3; i++) {
pthread_join(pro[i], NULL);
}
for(int i = 0; i < 3; i++) {
pthread_join(con[i], NULL);
}
pthread_mutex_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}