% FutureID - owns the ID counter for parallel.Future instances

% Copyright 2013-2020 The MathWorks, Inc.
classdef (Hidden) FutureID < handle
    methods (Static, Access = ?parallel.internal.queue.Future)
        function obj = buildNextID()
        % Get a single new ID
            obj = iGetNextID();
        end
        function vec = reserveIDs(N)
        % Get N new IDs
            vec = arrayfun(@(x) iGetNextID, 1:N);
        end
        
        function vec = reserveUIDs(N)
            vec = arrayfun(@(x) iGetNextUID, 1:N);
        end
            
    end
end

function id = iGetNextID()
    persistent COUNTER
    if isempty(COUNTER)
        COUNTER = 0;
        mlock;
    end
    COUNTER = COUNTER + 1;
    id = COUNTER;
end


function id = iGetNextUID()
    persistent UID_COUNTER
    if isempty(UID_COUNTER)
        UID_COUNTER = 0;
        mlock;
    end
    UID_COUNTER = UID_COUNTER + 1;
    id = UID_COUNTER;
end
