[英]OpenMP: parallel for(i;…) and i value
I have a following parallel snippet: 我有以下并行代码段:
#include <omp.h>
#include "stdio.h"
int main()
{
omp_set_num_threads(4);
int i;
#pragma omp parallel private(i)
{
#pragma omp for
for(i = 0;i < 10; i++) {
printf("A %d: %d\n", omp_get_thread_num(),i);
}
#pragma omp critical
printf("i %d: %d\n", omp_get_thread_num(), i );
}
}
I thought that after the loop, each thread will have i
equal to i
last value in the thread's loop. 我认为,在循环后,每个线程都有
i
等于i
在线程的循环最后一个值。 My desired output would be: 我想要的输出将是:
A 0: 0
A 0: 1
A 0: 2
A 3: 9
A 2: 6
A 2: 7
A 2: 8
A 1: 3
A 1: 4
A 1: 5
i 0: 3
i 3: 10
i 2: 9
i 1: 6
whereas what I get is: 而我得到的是:
A 0: 0
A 0: 1
A 0: 2
A 3: 9
A 2: 6
A 2: 7
A 2: 8
A 1: 3
A 1: 4
A 1: 5
i 0: -1217085452
i 3: -1217085452
i 2: -1217085452
i 1: -1217085452
How to make i
to hold last iteration's value? 如何使
i
保持上一次迭代的值? lastprivate(i)
makes i = 10
for all threads, and that is not what I want. lastprivate(i)
使所有线程的i = 10
,这不是我想要的。
It turns out you can't. 事实证明你做不到。 OpenMP alters program semantics.
OpenMP更改程序语义。
Parallel for loops are rewritten by the compiler according to well-defined set of rules. 编译器会根据定义良好的规则重写并行for循环。
This also implies you cannot break from, return from such a loop. 这也意味着您不能从这种循环中中断或返回。 You can also not directly manipulate the loop variable.
您也不能直接操作循环变量。 The loop condition can not call random functions or do any conditional expression, in short: a
omp parallel for
loop is not a for loop 简而言之,循环条件不能调用随机函数或任何条件表达式:
omp parallel for
循环不是 for循环
#include <omp.h>
#include "stdio.h"
int main()
{
omp_set_num_threads(4);
#pragma omp parallel
{
int i;
#pragma omp for
for(i = 0;i < 10; i++) {
printf("A %d: %d\n", omp_get_thread_num(),i);
}
#pragma omp critical
printf("i %d: %d\n", omp_get_thread_num(), i );
}
}
Thanks to sehe`s post, I figure out the following dirty trick that solves the problem 感谢sehe的帖子,我找出了以下解决问题的肮脏技巧
int i, last_i;
#pragma omp parallel private(i)
{
#pragma omp for
for(i = 0;i < 10; i++) {
printf("A %d: %d\n", omp_get_thread_num(),i);
last_i = i;
}
#pragma omp critical
printf("i %d: %d\n", omp_get_thread_num(), last_i );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.