// Question Nine
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
pthread_mutex_t lock;
typedef struct {
int start;
int stop;
int *array;
int *result;
} Job;
void *add (void *thing) {
int result = 0;
Job *job = (Job*) thing;
for (int i = job->start; i < (job->stop + 1); ++i) {
result += job->array[i];
}
pthread_mutex_lock(&lock);
*job->result += result;
pthread_mutex_unlock(&lock);
return 0;
}
int sarray(int n, int t, int *values) {
pthread_t tid[t];
pthread_mutex_init(&lock, NULL);
// Split into even nunber of threads by t
int thread_share = n/t;
int remaining = n;
int index = 0;
int result = 0;
Job work[t];
for (int i = 0; i < t; ++i) {
Job current = work[i];
current.start = index;
if (remaining < thread_share) {
current.stop = remaining;
} else {
current.stop = index + thread_share - 1;
}
current.array = values;
current.result = &result;
work[i] = current;
remaining -= thread_share;
index = current.stop + 1;
pthread_create(&tid[i], NULL, add, &work[i]);
}
for (int i = 0; i < t; i++) {
pthread_join(tid[i], NULL);
}
// pthread_mutex_destroy(&lock);
return result;
}
int main (int argc, char **argv) {
int array[10] = {1,2,3,4,5,6,7,8,9,10};
int result = sarray(10, 10, array);
printf("Result: %d\n", result);
return result;
}