Last active
November 14, 2016 14:53
-
-
Save kellielutze/57e2c2a45deeb67f45436c6c32adebf7 to your computer and use it in GitHub Desktop.
Multithreaded application to add an array of integers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment