【问题标题】:OMP - Reduce to a value based on another valueOMP - 根据另一个值减少到一个值
【发布时间】:2019-11-26 19:35:19
【问题描述】:

我正在尝试并行化一个简单的算法,以便为旅行商问题找到合适的解决方案。

path 是一个与城市对应的整数数组。在每次尝试中,选择path 数组的两个随机索引进行切换。此开关影响到前后节点的距离,总共有 4 个距离。如果将它们相加,我们可以推断出我们执行的切换是否会产生比旧路径更好或更差的路径。在前一种情况下,开关被保留,我们可以进行下一次尝试。

并行化此算法的一个想法是同时尝试N 不同的开关,并执行生成最短路径的开关。我目前的代码如下:

float switchCities(){

    int switchCandidates[NUM_THREADS][2];
    float minDist;

    #pragma omp parallel for reduction(*need help here*)
    for(int i=0; i<NUM_THREADS; i++){

        //selecting 2 random candidates excluding the first and last
        switchCandidates[i][0] = rand() % (N-1) + 1;
        switchCandidates[i][1] = rand() % (N-1) + 1;

        float oldDist = localDist(switchCandidates[i][0], switchCandidates[i][1]);
        float newDist = localSwitchedDist(switchCandidates[i][0], switchCandidates[i][1]);

        if(newDist >= oldDist){
            newDist = FLT_MAX;
        }

    }

    //perform the switch
    ....

    return minDist;
}

通过将无效的开关距离设置为某个较大的数字,我可以将距离减小到最小值,但是我对路径本身比对距离更感兴趣。是否可以执行减少,以便我最终得到导致最小距离的索引i

【问题讨论】:

    标签: c parallel-processing openmp reduction


    【解决方案1】:

    使用共享向量来保存信息,然后让一个线程使用该向量来确定最佳选择是什么:

    float switchCities(){
    
        int switchCandidates[NUM_THREADS][2];
        float minDist;
    
        std::vector<std::pair<float,int> > best(omp_get_max_threads(), std::make_pair<float,int>(9e999999, -1));
    
        #pragma omp parallel for
        for(int i=0; i<NUM_THREADS; i++){
            //selecting 2 random candidates excluding the first and last
            switchCandidates[i][0] = rand() % (N-1) + 1;
            switchCandidates[i][1] = rand() % (N-1) + 1;
    
            float oldDist = localDist(switchCandidates[i][0], switchCandidates[i][1]);
            float newDist = localSwitchedDist(switchCandidates[i][0], switchCandidates[i][1]);
    
            auto &my_best = best.at(omp_get_thread_num());
            if(newDist >= my_best.first){
                my_best.first = newDist;
                my_best.second = i;
            }
        }
    
        //have one thread look at the `best` vector and find the best value here
    
        return minDist;
    }
    

    【讨论】:

    • 我忘了在标签中添加 c 是我的错。数组可以代替向量吗?
    • @VlassisFo:是的,C 也可以。只需使用struct 定义一个适当大小的数组来携带信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2018-03-23
    相关资源
    最近更新 更多