A functional map is a function that applies a callback function to each element in an array and returns a list of callback return values. For example, in pseudocode, map(["hello", "world"], fn(x) => x + " meow")
would return ["hello meow", "world meow"]
Since function pointers can be passed as parameters in C, it is possible to implement a functional map like below:
void** fp_map(void** array, size_t len, void* (*execute)(void*))
{
// Allocate memory for return items
void** returns = malloc(sizeof(void*) * len);
if (returns == NULL) err(42, "Malloc failed, buy more ram");
// Map values
for (int i = 0; i < len; ++i)
returns[i] = execute(array[i]);
return returns;
}
If I write the following anonymous function in my main method, it would map ["hello", "world"]
to ["hello meow", "world meow"]
:
int main() {
char* arr[] = {"hello", "world"};
char** arr2 = fp_map((void**) arr, 2, ({ void* _func_ (void* x) {
char* buf = malloc(sizeof(char) * (strlen(x) + 7));
strcpy(buf, x);
strcat(buf, " meow");
return buf;
}; _func_; }));
for (int i = 0; i < 3; ++i)
printf("%s\n", arr2[i]);
}
Now, I want to implement a parallel map to speed things up. Since this is purely functional, calls to the callback function with the same parameters would return the same return values. How can I use multithreading so that each call to execute()
runs on a different thread, but still have the results return in an ordered array?