问题描述
我是OpenMP的新手,我只是尝试编写一个带有并行用于构造的小程序.我在理解程序输出时遇到麻烦.我不明白为什么3号线程会在1号和2号之前输出输出.有人可以给我一个解释吗?
I am new to OpenMP and I just tried to write a small program with the parallel for construct. I have trouble understanding the output of my program. I don't understand why thread number 3 prints the output before 1 and 2. Could someone offer me an explanation?
因此,程序为:
#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®Core™i5-2410M CPU.
My processor is a Intel(R) Core(TM) i5-2410M CPU with 4 cores.
谢谢!
推荐答案
OpenMP不保证不同线程在时间上执行语句的相对顺序.如果需要,OpenMP会将其留给程序员强加这样的顺序.通常,不需要,甚至在很多情况下都不希望这样做,这就是OpenMP保持默认行为的原因.及时施加这样的命令的成本可能是巨大的.
OpenMP makes no guarantees of the relative ordering, in time, of the execution of statements by different threads. OpenMP leaves it to the programmer to impose such ordering if it is required. In general it is not required, in many cases not even desirable, which is why OpenMP's default behaviour is as it is. The cost, in time, of imposing such an ordering is likely to be significant.
我建议您多次运行更大的测试,应该观察到事件的跨线程排序本质上是随机的.
I suggest you run much larger tests several times, you should observe that the cross-thread sequencing of events is, essentially, random.
这篇关于用于"for"的OpenMP输出.环形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!