So I'm playing with developing an algorithm to evenly distribute work among threads, but it's somewhat unique. The work being done is file comparisons where we have a list of files (let's say 10 files). We don't want to compare file 1 to file 1, so each file would skip comparing itself. File 1 would compare itself to files 2 through 10, file 2 would compare itself to files 3 through 10, etc. So as we move down the list of file compares, the number of file compares drops. Here is the little snippet I'm having issues with (specifically the do-while loop)
// Get first pass file chunks
printf("Split approximation: ");
for (int i = 0; i < num_threads; i++)
{
file_chunks[i] = (int)floor((double)num_file_compares / (double)num_threads);
printf("%d ", file_chunks[i]);
}
printf("\n");
// Adjust file chunks to contain all files
for (int i = 0; i < num_threads; i++)
{
file_chunk_sum = file_chunk_sum + file_chunks[i];
}
append_count = num_file_compares - file_chunk_sum;
printf("Need to append last %d\n", append_count);
append_index = num_threads;
do
{
printf("im in the do while...\n");
printf("append count is: %d\n", append_count);
printf("why am i here?\n");
append_index = append_index - 1;
file_chunks[append_index] = file_chunks[append_index] + 1;
append_count = append_count - 1;
} while (append_count > 0);
printf("Final split: ");
for (int i = 0; i < num_threads; i++)
{
printf("%d ", file_chunks[i]);
}
printf("\n");
With the input of 20 files (190 file compares) and 5 threads, the split approximation would be an even split of 38 file compares per thread. The append count is 0, but it still jumps into the do-while loop. Any idea why?
The output of those printf's is
Number of files: 20
Number of threads: 5
Number of file compares: 190
Split approximation: 38 38 38 38 38
Need to append last 0
im in the do while...
append count is: 0
why am i here?
Final split: 38 38 38 38 39
A 'do while' is always executed at least once. If you don't want it to behave that way, try using a regular 'while'.
Rather that using do...while, you just want to use while. This performs the check at the top of the loop instead of the bottom.
while (append_count > 0)
{
printf("im in the while...\n");
printf("append count is: %d\n", append_count);
printf("why am i here?\n");
append_index = append_index - 1;
file_chunks[append_index] = file_chunks[append_index] + 1;
append_count = append_count - 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With