为什么 omp 并行部分中的线程不会在其部分上划分?

Why won't the threads in the omp parallel section be divided on their sections?

本文关键字:其部 划分 线程 并行部 omp 为什么      更新时间:2023-10-16

我正在尝试使用OpenMP库并行实现三元搜索算法。我正在使用递归,这是我在代码实施中到目前为止所达到的。

这是搜索功能:

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标准中进一步阅读,并为此使用任务。它们比使用嵌套并行性更好地适合递归问题。