CC BY 4.0 (除特别声明或转载文章外)
如果这篇博客帮助到你,可以请我喝一杯咖啡~
#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);
}