CC BY 4.0 (除特别声明或转载文章外)
如果这篇博客帮助到你,可以请我喝一杯咖啡~
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
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
int n, *a, sum = 0;
sem_t sumMux;
void myMin()
{
int ret = a[0];
for (int i = 1; i < n; ++i)
ret = ret < a[i] ? ret : a[i];
sem_wait(&sumMux);
sum += ret;
sem_post(&sumMux);
}
void myMax()
{
int ret = a[0];
for (int i = 1; i < n; ++i)
ret = ret > a[i] ? ret : a[i];
sem_wait(&sumMux);
sum += ret;
sem_post(&sumMux);
}
void myAvg()
{
int ret = a[0];
for (int i = 1; i < n; ++i)
ret += a[i];
sem_wait(&sumMux);
sum += ret / n;
sem_post(&sumMux);
}
int main()
{
scanf("%d", &n);
a = malloc(sizeof(int) * n);
for (int i = 0; i < n; ++i)
scanf("%d", &a[i]);
pthread_t p[3];
sem_init(&sumMux, 0, 1);
pthread_create(&p[0], NULL, myMin, NULL);
pthread_create(&p[1], NULL, myMax, NULL);
pthread_create(&p[2], NULL, myAvg, NULL);
for (int i = 0, ret; i < 3; ++i)
pthread_join(p[i], NULL);
free(a);
printf("%d", sum);
}