1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/***********************************************************************8*****\
 * This is an illustration created in office hours.  It has not been tested. *|
\*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>

int* _make_array(size_t len, int value) {
    int* array = malloc(len * sizeof(*array));
    for(int i = 0; i < len; i++) {
        array[i] = value;
    }
    return array;
}

typedef struct _AdderArgs {
    int* lhs;
    int* rhs;
    int* result;
    size_t num_to_add;
} AdderArg;

void* _add_array_subset(void* a_arg) {
    AdderArg* a_adder_arg = a_arg;
    for(int i = 0; i < a_adder_arg -> num_to_add; i++) {
        a_adder_arg -> result[i] = a_adder_arg -> lhs[i] + a_adder_arg -> rhs[i];
    }
    return NULL;
}

int* add_arrays(int* lhs, int* rhs, size_t len, size_t num_threads) {
    int* result = malloc(len * sizeof(*result));

    // Create array of AdderArg objects, each of which will be passed to a thread.
    AdderArg*  args    = malloc(num_threads * sizeof(*args));

    // Create and start threads
    pthread_t* threads = malloc(num_threads * sizeof(*threads));
    size_t num_elements_per_thread = len / num_threads;  // except last one

    for(int start_idx = 0; start_idx + num_elements_per_thread - 1 < len;
                                   start_idx += num_elements_per_thread) {
        int thread_idx = start_idx / num_elements_per_thread;
        args[thread_idx] = (AdderArg) { .lhs        = &lhs[start_idx],
                                        .rhs        = &rhs[start_idx],
                                        .result     = &result[start_idx],
                                        .num_to_add = num_elements_per_thread };
        if(thread_idx == num_threads - 1) {  // last thread?
            args[thread_idx].num_to_add = len - start_idx;  // use up the rest
        }
        pthread_create(&threads[thread_idx], NULL, _add_array_subset, &args[thread_idx]);
    }

    // Wait for all threads to return.
    for(int i = 0; i < num_threads; i++) {
        pthread_join(threads[i], NULL);
    }

    free(threads);
    free(args);

    return result;
}

int main(int argc, char* argv[]) {
    size_t len = 256;
    size_t num_threads = 5;
    int* array5 = _make_array(len, 5);
    int* array7 = _make_array(len, 7);
    int* result = add_arrays(array5, array7, len, num_threads);
    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2019 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.