Our assignment involves creating a sorting algorithm that sorts an array of randomly generated integers. The array size if set as an argument when executing the program.
For testing, we print the first 10 elements of the already sorted array, along with the execution time.
Our implementation works correctly when we don't insert multi-threading in our function that generates the random array. However, when using parallel code, in about 10% of cases we get an unexpected result. For 12000000 size array as an example:
1st execution output: 0 1 2 2 4 7 7 9 9 9
2nd execution output: 0 1 1 1 1 2 4 4 7 7
3rd execution output: 0 1 1 1 1 2 2 2 4 4
4th execution output: 0 1 1 2 4 7 7 9 12 16
5th execution output: 0 10278907 1671508 1716191 145377 3825599 1265238 859463 6112391 11065992
nth execution output: more expected results and the occasional unexpected result.
At first, I thought the problem was the rand() function we used that wasn't thread safe. So I changed our function from this:
void randomizeArray(int* array, int size, int max_value) {
int i;
#pragma omp parallel for
for (i = 0; i < size; i++) {
array[i] = rand() % max_value;
}
}
To this:
void randomizeArray(int* array, int size, int max_value) {
int i;
unsigned int seed = 1;
#pragma omp parallel for
for (i = 0; i < size; i++) {
array[i] = rand_r(&seed) % max_value;
}
}
And the results are the same. A bunch of correctly sorted 1-2 digits output and the occasional not sorted array of large integers. Is this related to the randomize function? Or could it be something else?
Thank you in advance.