globals and parfor

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.

Leave a Comment