function [comm, workerIdxOfFirst] = commForWorld( action, comm, workerIdxOfFirst )
% commForWorld - SPMD helper function
% Stash the vector of communicators to be used by a world ResourceSet.  In
% the case of a parallel pool job, this differs from the 'world' communicator
% as understood by mpiCommManip because it only involves 'world' workers
% 2:spmdSize. Also, we store the 'world' spmdIndex offset here. This
% information is used to build remote parallel resource sets.
    
% Copyright 2008-2022 The MathWorks, Inc.
    
    persistent WORLDCOMM WORKERIDXFIRST
    if isempty( WORLDCOMM )
        WORLDCOMM = 'world';
        WORKERIDXFIRST = 1;
        mlock;
    end
    
    switch action
      case 'get'
        comm = WORLDCOMM;
        workerIdxOfFirst = WORKERIDXFIRST;
      case 'set'
        WORLDCOMM = comm;
        WORKERIDXFIRST = workerIdxOfFirst;
      case 'reset'
        WORLDCOMM = 'world';
        WORKERIDXFIRST = 1;
    end
end
