generated from mobile-os-dku-cis-mse/mse-os-hw2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprod_cons.c
118 lines (108 loc) · 2.34 KB
/
prod_cons.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
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
typedef struct sharedobject {
FILE *rfile;
int linenum;
char *line;
pthread_mutex_t lock;
int full;
} so_t;
void *producer(void *arg) {
so_t *so = arg;
int *ret = malloc(sizeof(int));
FILE *rfile = so->rfile;
int i = 0;
char *line = NULL;
size_t len = 0;
ssize_t read = 0;
while (1) {
read = getdelim(&line, &len, '\n', rfile);
if (read == -1) {
so->full = 1;
so->line = NULL;
break;
}
so->linenum = i;
so->line = strdup(line); /* share the line */
i++;
so->full = 1;
}
free(line);
printf("Prod_%x: %d lines\n", (unsigned int)pthread_self(), i);
*ret = i;
pthread_exit(ret);
}
void *consumer(void *arg) {
so_t *so = arg;
int *ret = malloc(sizeof(int));
int i = 0;
int len;
char *line;
while (1) {
line = so->line;
if (line == NULL) {
break;
}
len = strlen(line);
printf("Cons_%x: [%02d:%02d] %s",
(unsigned int)pthread_self(), i, so->linenum, line);
free(so->line);
i++;
so->full = 0;
}
printf("Cons: %d lines\n", i);
*ret = i;
pthread_exit(ret);
}
int main (int argc, char *argv[])
{
pthread_t prod[100];
pthread_t cons[100];
int Nprod, Ncons;
int rc; long t;
int *ret;
int i;
FILE *rfile;
if (argc == 1) {
printf("usage: ./prod_cons <readfile> #Producer #Consumer\n");
exit (0);
}
so_t *share = malloc(sizeof(so_t));
memset(share, 0, sizeof(so_t));
rfile = fopen((char *) argv[1], "r");
if (rfile == NULL) {
perror("rfile");
exit(0);
}
if (argv[2] != NULL) {
Nprod = atoi(argv[2]);
if (Nprod > 100) Nprod = 100;
if (Nprod == 0) Nprod = 1;
} else Nprod = 1;
if (argv[3] != NULL) {
Ncons = atoi(argv[3]);
if (Ncons > 100) Ncons = 100;
if (Ncons == 0) Ncons = 1;
} else Ncons = 1;
share->rfile = rfile;
share->line = NULL;
pthread_mutex_init(&share->lock, NULL);
for (i = 0 ; i < Nprod ; i++)
pthread_create(&prod[i], NULL, producer, share);
for (i = 0 ; i < Ncons ; i++)
pthread_create(&cons[i], NULL, consumer, share);
printf("main continuing\n");
for (i = 0 ; i < Ncons ; i++) {
rc = pthread_join(cons[i], (void **) &ret);
printf("main: consumer_%d joined with %d\n", i, *ret);
}
for (i = 0 ; i < Nprod ; i++) {
rc = pthread_join(prod[i], (void **) &ret);
printf("main: producer_%d joined with %d\n", i, *ret);
}
pthread_exit(NULL);
exit(0);
}