forked from huannguyen2008/os2019
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08.practical.work.pthread.c
71 lines (60 loc) · 1.52 KB
/
08.practical.work.pthread.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define BUFFER_SIZE 10
typedef struct {
char type; // 0=fried chicken, 1=French fries
int amount; // pieces or weight
char unit; // 0=piece, 1=gram
} item;
item buffer[BUFFER_SIZE];
int first = 0;
int last = 0;
void produce(item *i) {
while ((first + 1) % BUFFER_SIZE == last) {
// do nothing -- no free buffer item
}
memcpy(&buffer[first], i, sizeof(item));
first = (first + 1) % BUFFER_SIZE;
}
item *consume() {
item *i = malloc(sizeof(item));
while (first == last) {
// do nothing -- nothing to consume
}
memcpy(i, &buffer[last], sizeof(item));
last = (last + 1) % BUFFER_SIZE;
return i;
}
item* initItem(char type, int amount, char unit){
item* i = malloc(sizeof(item));
i->type = type;
i->amount = amount;
i->unit = unit;
return i;
}
void *producer(void *para) {
item fc={'1',0,'1'}, Ff1={'1',3,'0'}, Ff2={'1',3,'1'};
produce(&fc);
produce(&Ff1);
produce(&Ff2);
}
void display(item* i) {
printf("Type: %c Amount(s): %d Unit: %c\n",i->type,i->amount,i->unit);
}
void *consumer(void *para) {
display(consume());
display(consume());
}
int main() {
pthread_t tid1,tid2;
pthread_create(&tid1, NULL, producer, NULL);
pthread_create(&tid2, NULL, consumer, NULL);
printf("After produce: First: %d Last %d \n", first, last);
consume();
printf("After consume: First: %d Last %d \n", first, last);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}