Homework 4 计算数组最小值+最大值+平均值的和 wu-kan

题目链接

#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);
}