我正在尝试使用与OpenMP库并行的编译指示omp来实现三元搜索算法。我正在使用递归,这是到目前为止我在代码实现中所达到的目标。
这是搜索功能:
int ternarySearch(int arr[], int size, int left, int right, int num)
{
if (left < 0 || right > size - 1 || left > right){
return -1;
}
else if (num == arr[left]){
return left-1;
}
else if (num == arr[right]){
return right-1;
}
else if (num < arr[left]){
return ternarySearch(arr, size, left - 1, right, num);
}
else if (num > arr[left] && num < arr[right]){
return ternarySearch(arr, size, left + 1, right - 1, num);
}
else if (num > arr[right]){
return ternarySearch(arr, size, left, right + 1, num);
}
}
这是主函数中调用ternarySearch函数的部分:
omp_set_num_threads(4);
int quarter = size / 4;
/*Using Recursion*/
cout << endl << "Parallel Using Recursion: " << endl << endl;
bool isFound = false;
double paraRecStartTime = omp_get_wtime();
#pragma omp parallel shared(isFound)
{
int id, start, end, left, right, result;
id = omp_get_thread_num();
start = id*quarter;
end = start + quarter;
left = (quarter / 3) + start;
right = end - (quarter / 3);
cout << id << endl;
result = ternarySearch(arr, end, left, right, num);
if(result != -1) {
cout << "Found by thread " << id << " in index " << result << endl;
isFound = true;
}
}
double paraRecRunTime = omp_get_wtime() - paraRecStartTime;
cout << "Ternary Search took " << paraRecRunTime << " sec using 4 threads." << endl << endl;
if (isFound == false) {
cout << "Number does not exist in the array." << endl << endl;
}
问题在于,在输出中,所有线程都会找到该元素,而应该为每个线程仅分配一部分数组,以便使用三元搜索算法在其中进行搜索。有人可以帮助我知道我哪里出了错吗?
最佳答案
进一步阅读OpenMP标准,并为此使用任务。它们比使用嵌套并行性更好地解决了递归问题。
关于c++ - 为什么在omp并行部分中的线程不按其部分划分?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43641214/