编辑:更改了代码和措辞以使我的疑问更加明确
很长一段时间以来,我一直在努力使用 OpenMP 并行化 C 中的循环,并想知道我应该如何应对这一挑战。该循环由以下部分组成(如果您想知道该循环是集成在模拟退火算法中的主循环):
for(attempt = 0; attempt < SATISFIED; attempt++) {
i = (rand() % (len-1)) + 1;
j = i + (rand() % (len-i));
if(...) {
...
//Update global static variables:
if(dst < best_distance)
set_best(dst, path);
//Stop this attempt:
attempt = -1;
}
//Decrease the temperature:
temp = change_temp(temp);
}
这个循环的问题是迭代的次数不能通过它的条件来计算,所以我想出了一种不同的方法来编写这个循环,以便能够使用 openmp:
while(keepGoing){
keepGoing = 0;
#pragma omp parallel for default(none) shared(len, best_distance, best_path, distances, avg_distance, path) private( i, j, seed, swp_dst) lastprivate(dst, temp, keepGoing) firstprivate(dst, temp, abort, keepGoing)
for(attempt = 0; attempt < SATISFIED; attempt++) {
#pragma omp flush (abort)
if (!abort) {
seed = omp_get_thread_num();
i = (rand_r(&seed) % (len-1)) + 1;
j = i + (rand_r(&seed) % (len-i));
//Update progress:
#pragma omp critical
{
if(...) {
...
//Update global static variables:
if(dst < best_distance)
set_best(dst, path);
//Stop this attempt:
keepGoing = 1;
abort = 1;
#pragma omp flush (abort)
#pragma omp flush (keepGoing)
}
}
//Decrease the temperature:
temp = change_temp(temp);
}
}
}
但是,由于我不明白的原因,此解决方案与我在输出之前编写的顺序版本不同... openmp 指令是否放置得当?或者我应该以不同的方式使用它们?提前感谢您的任何回答。