c++ - 为什么 omp 并行部分中的线程不按其部分划分?

标签 c++ search parallel-processing openmp pragma

我正在尝试使用 OpenMP 库中的 pragma omp parallel 来实现三元搜索算法。我正在使用递归,这是到目前为止我在代码实现中所达到的效果。

这是搜索功能:

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/

相关文章:

c++ - 使用迭代器范围将单个元素附加到容器

c++ - 算术 C++ 运算符

c - 多进程无锁

javascript - javascript 是 "truly parallel"吗?

c++ - 使用 C++ 进行货币格式化

c++ - boost::filesystem:从 1.34.1 更新到当前版本

php - 使用多个 LIKE 条件搜索查询无法按预期工作

string - 用于索引整个文档的数据结构和用于快速搜索任何大小子字符串的算法

Pythonic 方式查找值在范围列表中的位置

javascript - 在javascript中将并行字符串化(序列化)到JSON