用于“for”循环的OpenMP输出

时间:2014-01-09 19:31:22

标签: parallel-processing openmp

我是OpenMP的新手,我只是尝试编写一个带有parallel for construct的小程序。我无法理解程序的输出。我不明白为什么第3号线在1和2之前打印输出。有人能给我一个解释吗?

所以,该计划是:

#pragma omp parallel for
for (i = 0; i < 7; i++) {
    printf("We are in thread  number %d and are printing %d\n",
         omp_get_thread_num(), i);
}

,输出为:

We are in thread number 0 and are printing 0
We are in thread number 0 and are printing 1
We are in thread number 3 and are printing 6
We are in thread number 1 and are printing 2
We are in thread number 1 and are printing 3
We are in thread number 2 and are printing 4
We are in thread number 2 and are printing 5

我的处理器是具有4核的Intel(R)Core(TM)i5-2410M CPU。

谢谢!

2 个答案:

答案 0 :(得分:1)

OpenMP不保证不同线程执行语句的时间相对排序。如果需要,OpenMP将它留给程序员进行这样的排序。通常,在许多情况下甚至不需要它是不需要的,这就是OpenMP默认行为的原因。实施这种排序的时间成本可能很高。

我建议你多次运行更大的测试,你应该观察到事件的跨线程排序基本上是随机的。

答案 1 :(得分:1)

如果您想按顺序打印,则可以使用ordered构造

#pragma omp parallel for ordered
for (i = 0; i < 7; i++) {
    #pragma omp ordered
    printf("We are in thread  number %d and are printing %d\n",
         omp_get_thread_num(), i);
}

我认为这需要来自较大迭代的线程等待迭代次数较低的线程,因此它会对性能产生影响。你可以在这里看到http://bisqwit.iki.fi/story/howto/openmp/#ExampleCalculatingTheMandelbrotFractalInParallel 这使用ordered将Mandelbrot设置为字符。比使用ordered快得多的解决方案是将字符并行填充数组,然后连续绘制它们(尝试代码)。由于一个人使用OpenMP来提高性能,我从来没有找到使用ordered的理由,但我确信它在某个地方有用。