全局变量和 parfor [英] globals and parfor
问题描述
在 parfor
循环中,我试图调用一个访问 global
的函数但无济于事.
Inside a parfor
loop, I am trying to call a function that accesses a global
to no avail.
函数
function a = getA()
global OPTIONS;
a=OPTIONS.PROBLEM.A;
end
循环:
parfor i=1:3
b=getA();
end
错误:
Error using parallel_function (line 589)
Attempt to reference field of non-structure array.
我做错了什么?
推荐答案
来自 parfor 上的 rel="nofollow noreferrer">文档:
From the documentation on parfor
:
parfor 循环的主体不能包含全局或持久变量声明.
The body of a parfor-loop cannot contain global or persistent variable declarations.
在您的问题的上下文中,即在 parfor
中调用一个函数,该函数又引用了一个 global
,这转化为:parfor
可能不会给出预期或有意义的结果".
In the context of your problem, i.e., calling a function within the parfor
that in turn references a global
, this translates into: "parfor
will probably not give expected or meaningful results".
这是完全有道理的.考虑以下
This makes perfect sense. Consider the following
Lab 1: Lab 2:
GetB(); GetB();
如果GetB()
的内容是这样的:
function GetB()
global B;
%# do something useful
B = rand;
end
当Lab 1
引用B
时,它的值是什么?在 Lab 2
上?rand
的不同结果如何传达?这将是一团糟!
what will the value of B
be when it is referenced on Lab 1
? and on Lab 2
? How are the different outcomes of rand
communicated? It's going to be a mess!
编写适用于 parfor
循环的代码可能会是一个真正的痛苦,因为该代码来自只考虑正常 for
循环的东西.通常,当您事先知道要编写一段计算密集型的 Matlab 代码时,请从一开始就将所有函数和循环编写为 parfor
循环.只有这样,才能避免此类 bug 花费您一天的时间来对您的函数进行转码.
Writing code suited for parfor
loops can be a real pain when that code comes from something that only had normal for
-loops in mind. Generally, when you know beforehand you're going to write a computationally intensive piece of Matlab code, write all functions and loops as parfor
loops right from the beginning. That is the only way that bugs like these will not cost you a day on transcoding your functions.
从 for
转换为 parfor
绝非易事.
这篇关于全局变量和 parfor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!