1

I am wondering how can I easily access the global variable in calling a function within a parfor loop? For example the sample code is as follows,

global a
a = 132.1;

A = [0, 0, 0];

for i=1:3
    A(i) = test(i);
end

And the test function is

function f = test(v)
global a
f = a+v;

The code should be correct in this format, however, if I change for to parfor, it arises problem. I think the major problem is the global variable a. So how can I modify the code? Although in this example, the modification is easy and no need for parfor, but my real code is really complicated, the problem gets down to the same one.

Terry
  • 179
  • 3
  • 9
  • 3
    Why not pass `a` to your function? Particularly if `a` isn't changing this is your best bet really. If it *is* changing, you should reconsider using `parfor` at all. – Suever Aug 05 '16 at 20:14

1 Answers1

1

The problem is with the parfor and the global variables:

There are two restrictions.

You cannot place a GLOBAL declaration directly inside a PARFOR loop
The MATLAB workers executing the body of your PARFOR loop are separate MATLAB processes, and the values of global variables are not synchronised

So, while you can use GLOBAL variables within functions called from the body of your PARFOR loop, they probably do not behave as you wish.

So in my opinion, you can pass the a variable to the loop and avoid global variables which is a good rule for functional programming and for programming in general. Also there are other solutions like this:

http://www.mathworks.com/matlabcentral/fileexchange/31972-worker-object-wrapper

anquegi
  • 11,125
  • 4
  • 51
  • 67
  • not really a convenient solution, especially if you're dealing with physics problems...consider a function inside a parforloop wich call several other functions, where all of them need a bunch of phyiscal constant..should I get used to passing 60+ constants to each function? There should be a way to broadcast global variables before parfor, just like it's handeled in C/C++/Fortran and MPI – OD IUM Feb 28 '20 at 11:38
  • @ODIUM You want to create functions for your constants, don’t use global variables for that. For example, `pi` is a function. If 60+ functions is too many, create one function that returns a struct with all constants. – Cris Luengo Jan 01 '22 at 04:07