Zurück zur SP1 Übersicht
sum.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "sem.h"
static void *sumRow(void *);
struct param {
int index;
};
static double a[100][100];
static double sum;
static SEM *s;
int main(void) {
s = semCreate(1);
for(int i = 0; i < 100; i++) {
for(int j = 0; j < 100; j++) {
a[i][j] = 1;
}
}
pthread_t tids[100];
struct param args[100];
for (int i = 0; i < 100; i++) {
args[i].index = i;
pthread_create(&tids[i], NULL, sumRow, &args[i]); }
for (int i = 0; i < 100; i++) {
pthread_join(tids[i], NULL); }
printf("%lf\n", sum); fflush(stdout); }
static void *sumRow(void *arg) {
struct param *par = (struct param *) arg;
double localSum = 0;
for (int j = 0; j < 100; j++) {
localSum += a[par->index][j];
}
P(s);
sum += localSum;
V(s);
return NULL;
}