试图让一个简单的 OpenMP 循环运行,但我不断收到奇怪的输出。它没有直接从 1 到 1000 列出,而是从 501 到 750,然后从 1 到 1000。我猜这是线程问题?我正在 VS2013 上编译和运行。
#include <stdio.h>
#include <math.h>
int main(void)
{
int counter = 0;
double root = 0;
// OPEN MP SECTION
printf("Open MP section: \n\n");
getchar(); //Pause
#pragma omp parallel for
for (counter = 0; counter <= 1000; counter++)
{
root = sqrt(counter);
printf("The root of %d is %.2f\n", counter, root);
}
return(0);
}
最佳答案
OpenMP 的全部点是并行运行,将工作分配给不同的执行引擎。
因此,循环的各个迭代很可能是无序完成的,因为这是多线程的本质。
虽然并行进行计算可能有意义(因此可能会乱序),但这并不是您真正想要的打印结果.
确保以正确顺序打印结果的一种方法是将打印推迟到并行执行完成之后。换句话说,并行化计算但串行化输出。
这当然意味着能够在并行操作运行时将信息存储在例如数组中。
换句话说,像这样:
// Make array instead of single value.
double root[1001];
// Parallelise just the calculation bit.
#pragma omp parallel for
for (counter = 0; counter <= 1000; counter++)
root[counter] = sqrt(counter);
// Leave the output as a serial operation,
// once all parallel operations are done.
for (counter = 0; counter <= 1000; counter++)
printf("The root of %d is %.2f\n", counter, root[counter]);
关于c - C 错误输出中的简单 OpenMP For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27762711/