问题描述
使用c ++ openmp 3.1,我实现了一个max reduce,它存储对象向量的整数变量(分数)的最大值.但我也想存储矢量索引,以使分数最高的对象获得访问.我当前不成功的实现如下所示:
Using c++ openmp 3.1 I implemented a max reduction which stores the maximum value of integer variable (score) of an vector of objects (s). But I also want to store the vector index to acces the (s) object with the maximum score.My current unsuccesfull implementation looks like this:
//s is a vector of sol objects which contain apart from other variables an integer score variable s[].score
int bestscore = 0;
int bestant = 0;
#pragma omp parallel shared(bestant)
{//start parallel session
#pragma omp for nowait reduction(max : bestscore)
for (int ant = 0; ant<maxsols; ++ant) // for all ants
{
//procedures on s[ant] object which update the int s[ant].score
if (s[ant].score > bestscore)
{
//find the object with the highest score
bestscore = s[ant].score;
bestant = ant;//i also want know which ant has the highest score
}
}
}
代码会编译并运行.找到了最大的最高分,但Bestant获得了一个随机索引.链接到完成速度最快的线程的蚂蚁将存储在bestant中.bestscore以0开头,因此在大多数情况下s [ant] .score会获得更高的分数,并且bestscore和bestant也会更新. 我认为我需要一个简化运算符来处理诸如更新最佳分数"之类的防腐剂.
The code compiles and runs. the maximum bestscore is found but bestant gets a random index. The ant linked to the fastest thread to finish gets stored in bestant.bestscore start with a value of 0 so in most cases s[ant].score will have a higher score and bestscore and bestant are updated. I think I need a reduction operator for bestant like "on update of bestscore".
推荐答案
尝试一下
int bestscore = 0;
int bestant = 0;
#pragma omp parallel
{
int bestscore_private = 0;
int bestant_private = 0;
#pragma omp for nowait
for (int ant = 0; ant<maxsols; ++ant) {
if (s[ant].score > bestscore_private) {
bestscore_private = s[ant].score;
bestant_private = ant;
}
}
#pragma omp critical
{
if(bestscore_private>bestscore) {
bestscore = bestscore_private;
bestant = besant_private;
}
}
}
这篇关于omp最大减少量与索引存储量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!