-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpc2.c
122 lines (96 loc) · 1.95 KB
/
pc2.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define N 1000
#define MAX_SEC 1000000 //1 second
#define gotoxy(x, y) printf("%c[%d;%df", 0x1B, x, y)
sem_t mutex, empty, full;
int buffer[N];
int n, front=0, rear=0, cnt=0;
void push(int x)
{
if(cnt==N)
return;
buffer[rear] = x;
rear = (rear +1)%N;
cnt++;
}
int pop()
{
if(cnt==0)
return -1;
int ret = buffer[front];
front = (front +1)%N;
cnt--;
return ret;
}
void *produce(void *iterations)
{
int tim;
for(int i=0; i<*(int *)iterations; i++)
{
//Produce Item
int item = rand()%N;
sem_wait(&empty);
sem_wait(&mutex);
//CS
tim = rand()%MAX_SEC;
usleep(tim);
//Push Item
push(item);
sem_post(&mutex);
sem_post(&full);
//NON CS
gotoxy(i+3, 0);
printf("Produced item : %d", item);
gotoxy(5, 60);
printf("Items in buffer : %2d\n", cnt);
fflush(stdout);
}
}
void *consume(void *iterations)
{
int tim;
for(int i=0; i<*(int *)iterations; i++)
{
int item;
sem_wait(&full);
sem_wait(&mutex);
//CS
tim = rand()%MAX_SEC;
usleep(tim);
//Remove Item
item = pop();
sem_post(&mutex);
sem_post(&empty);
//NON CS
gotoxy(i+3, 30);
printf("Consumed item : %d", item);
gotoxy(5, 60);
printf("Items in buffer : %2d\n", cnt);
fflush(stdout);
}
}
int main()
{
system("clear");
srand(time(0));
pthread_t producer, consumer;
int iterations_consume = rand()%10 +6; //(3, 9)
int iterations_produce = rand()%10 +iterations_consume;
printf("Enter size of Buffer : ");
scanf("%d", &n);
sem_init(&mutex, 0, 1); //Initial Value 1
sem_init(&empty, 0, n); //Initial value n
sem_init(&full, 0, 0); //Initial value 0
pthread_create(&producer, NULL, produce, &iterations_produce);
pthread_create(&consumer, NULL, consume, &iterations_consume);
pthread_join(producer, NULL);
pthread_join(consumer, NULL);
sem_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
gotoxy(iterations_produce+4, 0);
}