-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathejercicio6.c
More file actions
107 lines (97 loc) · 2.06 KB
/
ejercicio6.c
File metadata and controls
107 lines (97 loc) · 2.06 KB
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
#include <stdio.h>
#include <omp.h>
#define MAXWORK 40
int work[MAXWORK],
nwork=0,
nextput=0,
nextget=-1,
breaksum,
done = 0,
psum,csum,
pwork,
*cwork,
nth,
void next(int *m)
{ (*m)++;
if (*m >= MAXWORK) *m = 0;
}
void putwork(int k)
{ int put = 0;
while (!put) {
if (nwork < MAXWORK) {
#pragma omp critical
{ work[nextput] = k;
if (nwork == 0) nextget = nextput;
next(&nextput);
nwork++;
put = 1;
}
}
else sched_yield();
}
}
int getwork()
{ int k,get=0;
while (!get) {
if (done && nwork == 0) return -1;
#pragma omp critical
{
if (nwork > 0) {
k = work[nextget];
next(&nextget);
nwork--;
if (nwork == 0) nextget = -1;
get = 1;
}
}
}
return k;
}
void dowork()
{
#pragma omp parallel
{ int me = omp_get_thread_num(),
num;
#pragma omp single
{ int i;
nth = omp_get_num_threads();
printf("there are %d threads\n",nth);
cwork = (int *) malloc(nth*sizeof(int));
for (i = 1; i < nth; i++) cwork[i]=0;
}
#pragma omp barrier
if (me == 0) {
pwork = 0;
while (1) {
num = rand() % 100;
putwork(num);
psum += num;
pwork++;
if (psum > breaksum) {
done = 1;
break;
}
}
}
else {
while (1) {
num = getwork();
if (num == -1) break;
cwork[me]++;
#pragma omp atomic
csum += num;
}
}
}
}
int main(int argc, char **argv)
{ int i;
breaksum = atoi(argv[1]);
dowork();
printf("sum by producer: %d\n",psum);
printf("sum by consumers: %d\n",csum);
printf("work by producer: %d\n",pwork);
printf("work by consumers:\n");
for (i = 1; i < nth; i++)
printf("%d\n",cwork[i]);
}