Created
March 28, 2015 01:48
-
-
Save topnotcher/840a7f800d8a9b9306d1 to your computer and use it in GitHub Desktop.
This file contains 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
#include <pthread.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
typedef struct { | |
int result; | |
int size; | |
int numbers[]; | |
} calc_t; | |
typedef struct { | |
pthread_t thread; | |
char *name; | |
void *(*fn)(void*); | |
int expected; | |
calc_t *data; | |
} test_fn; | |
void *average(void *data); | |
void *min(void *data); | |
void *max(void *data); | |
int main(void) { | |
test_fn threads[] = { | |
{ .fn = average, .expected = 82, .name = "average" }, | |
{ .fn = max, .expected = 95, .name = "max" }, | |
{ .fn = min, .expected = 72, .name = "min" } | |
}; | |
int numbers[] = {90,81,78,95,79,72,85}; | |
for (int i = 0; i < sizeof(threads)/sizeof(threads[0]); ++i) { | |
threads[i].data = malloc(sizeof(calc_t) + sizeof(numbers)); | |
memcpy(&threads[i].data->numbers, numbers, sizeof(numbers)); | |
threads[i].data->size = sizeof(numbers)/sizeof(numbers[0]); | |
int result = pthread_create(&(threads[i].thread), NULL, threads[i].fn, (void*)(threads[i].data)); | |
//shitty error handling. | |
if (result) | |
fprintf(stderr, "pthread_create[%d] returned %d\n", i, result); | |
} | |
for (int i = 0; i < sizeof(threads)/sizeof(threads[0]); ++i) { | |
int retval; | |
int result = pthread_join(threads[i].thread, NULL); | |
//shitty error handling. | |
if (result) { | |
fprintf(stderr, "pthread_join[%d] returned %d\n", i, result); | |
} else { | |
printf("[%s] expected: %d; actual: %d\n", threads[i].name, threads[i].expected, threads[i].data->result); | |
} | |
} | |
return 0; | |
} | |
void *average(void *data) { | |
calc_t *job = (calc_t*)data; | |
int result = 0; | |
for (int i = 0; i < job->size; ++i) { | |
result += job->numbers[i]; | |
} | |
job->result = result/job->size; | |
pthread_exit(0); | |
} | |
void *min(void *data) { | |
calc_t *job = (calc_t*)data; | |
int result; | |
for (int i = 0; i < job->size; ++i) { | |
if (job->numbers[i] < result || i == 0) | |
result = job->numbers[i]; | |
} | |
job->result = result; | |
pthread_exit(0); | |
} | |
void *max(void *data) { | |
calc_t *job = (calc_t*)data; | |
int result; | |
for (int i = 0; i < job->size; ++i) { | |
if (job->numbers[i] > result || i == 0) | |
result = job->numbers[i]; | |
} | |
job->result = result; | |
pthread_exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment