Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

matlab - globals and parfor

Inside a parfor loop, I am trying to call a function that accesses a global to no avail.

The function

function a = getA()
   global OPTIONS;
   a=OPTIONS.PROBLEM.A;
end

The loop:

parfor i=1:3
    b=getA();
end

The error:

Error using parallel_function (line 589)

Attempt to reference field of non-structure array.

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the documentation on parfor:

The body of a parfor-loop cannot contain global or persistent variable declarations.

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();

if the contents of GetB() is this:

function GetB()
    global B;

    %# do something useful

    B = rand;

 end

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!

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.

Converting from for to parfor is not at all trivial.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...