gpt4 book ai didi

c - 并行化变量声明是否有益?

转载 作者:太空宇宙 更新时间:2023-11-04 02:24:21 25 4
gpt4 key购买 nike

我想知道在编写并行程序时将变量声明插入并行部分是否有好处?因为阿姆达尔定律说,如果程序的更多部分是并行的,那就更好了,但我看不出并行化变量声明和返回语句的意义,例如,这是正常的并行代码:

#include <omp.h>

int main(void) {
int a = 0;
int b[5];

#pragma omp parallel
{
#pragma omp for
for (int i = 0; i < 5; ++i) {
b[i] = a;
}
}

return 0;
}

写这个关于 Amdahl 定律是否有益(因此程序的 100% 是并行的):

#include <omp.h>

int main(void) {
#pragma omp parallel
{
int a = 0;
int b[5];
#pragma omp for
for (int i = 0; i < 5; ++i) {
b[i] = a;
}

return 0;
}
}

最佳答案

这些代码不等价:在第一种情况下,a 和 b 是共享变量(因为共享是变量的默认行为),在第二种情况下,这些是线程私有(private)变量,不存在于平行区域。

此外,第二段代码中并行区域内的return语句是非法的,肯定会导致编译错误。

例如在这个 OpenMP 4.0 reference card 中看到的

An OpenMP executable directive applies to the succeeding structured block or an OpenMP construct. Each directive starts with #pragma omp. The remainder of the directive follows the conventions of the C and C++ standards for compiler directives. A structured-block is a single statement or a compound statement with a single entry at the top and a single exit at the bottom.

包含 return 语句的 block 不是结构化 block ,因为它在底部没有单个导出(即右大括号 } 不是仅退出,因为 return 是另一个)。它可能不合法地遵循 #pragma omp parallel 指令。

关于c - 并行化变量声明是否有益?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53427091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com