globals and parfor

前端 未结 2 1748
南方客
南方客 2020-12-10 17:10

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

The function

function a = getA()
         


        
2条回答
  •  北海茫月
    2020-12-10 17:54

    GLOBAL data is hard to use inside PARFOR because each worker is a separate MATLAB process, and global variables are not synchronised from the client (or any other process) to the workers. It would work if you initialized the global data from a separate function on the workers. (As Rody points out, using the global keyword directly in the body of a PARFOR loop is not allowed - however, separate functions can do this). So, it would be legal to do this:

    parfor ii=1:matlabpool('size')
      myFcnWhichSetsUpGlobalData(); %# defines global OPTIONS
    end
    parfor ii=1:N
      result(ii) = myFcnWhichUsesGlobalData(); %# reads global OPTIONS
    end
    

    I would personally attempt to remove GLOBAL data from your application - it will make it work better with PARFOR, and it will make dependencies clearer.

    One further option to explore is my Worker Object Wrapper which is designed to stop you having to transfer data to the workers multiple times. You might use it this way:

    options = buildOptions();
    w_options = WorkerObjWrapper(options);
    parfor ii=1:N
      result(ii) = myFcnNeedingOptions(ii, w_options.Value);
    end
    

提交回复
热议问题