Building on top of this answer, I would like to make a program that forks itself to distribute a large number of independent computations over the CPUs of a machine. The computations output a number in the set {0, ..., n - 1}. My goal is simply to count the number of occurrences of each output in an array of size n.
To be clear, here is what the main loop in each of the child processes would look like:
for (i = start_range_for_this_process; i < end_range_for_this_process; i++)
{
input = generate_input(i);
output = the_computation(input);
count[output]++;
}
My question is the following: Is the answer I linked to above safe if many processes try to increment the same entry in the count array at the same time? If not, is there a way to make the processes use the array one at a time by asking them to lock it when it is free and wait when it is not free?
I tried searching on the web, but I didn't find what I was looking for. I might not be using the right keywords, since I am not very experienced with concurrent programming. Thanks for any help!