This repository has been archived by the owner on Feb 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPnC.cpp
84 lines (80 loc) · 1.69 KB
/
PnC.cpp
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
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <semaphore.h>
#include <pthread.h>
void *producer(void*param);
void *consumer(void*param);
int *myBuffer;
int itemCounter=0;
int bufferSize;
sem_t empty,full, binary;
int askForNumber(){
int i;
printf( "Enter a number:");
scanf("%d", &i);
return i;
}
using namespace std;
int main(int argc, char const *argv[]) {
cout<<"Size of buffer\n";
bufferSize= askForNumber();
myBuffer= (int*)calloc(bufferSize,sizeof(int));
sem_init(&empty,0,bufferSize);
sem_init(&full,0,0);
sem_init(&binary,0,1);
// thread identifier
pthread_t tid[2];
//thread attributes
pthread_attr_t attr;
// default attributes
pthread_attr_init(&attr);
//create pthreadh
pthread_create(&tid[0], &attr,producer, NULL);
pthread_create(&tid[1], &attr,consumer, NULL);
pthread_join(tid[0],NULL);
pthread_join(tid[1],NULL);
return 0;
}
int produceItem(){
return (rand()%50)+1;
}
void addItem(int item, int bufferSize){
int x;
for(x=0; x< bufferSize; x++){
if(myBuffer[x]==0){
printf("Produced %d to position %d\n",item,x );
myBuffer[x]=item;
break;
}
}
}
void consumeItem(){
int x;
for(x=0; x< bufferSize; x++){
if(myBuffer[x]!=0){
printf("Consumed Item %d in position %d\n",myBuffer[x],x );
myBuffer[x]=0;
break;
}
}
}
void *producer(void* param){
do {
int item= produceItem();
sem_wait(&empty);
sem_wait(&binary);
addItem(item,bufferSize);
sem_post(&binary);
sem_post(&full);
} while(1);
}
void *consumer(void* param){
do {
sem_wait(&full);
sem_wait(&binary);
consumeItem();
sem_post(&binary);
sem_post(&empty);
} while(1);
}