%Example skeleton code for spmd

% Set max usable threads to be equal to how many cores were granted for our job
NSLOTS = str2num(getenv('NSLOTS'));
maxNumCompThreads(NSLOTS);

% Check to see if we already have a parpool, if not create one with our desired parameters
poolobj = gcp('nocreate');
if isempty(poolobj)
	myCluster=parcluster('local');
	%Necessary so multiple parpool jobs don't overwrite other's temp files
	myCluster.JobStorageLocation = getenv('TMPDIR');
	poolobj = parpool(myCluster, NSLOTS);
end

n=1000;

schunk=int32(linspace(1,n,NSLOTS+1));
echunk=schunk-1;
temp=sort([schunk, echunk]);
chunk = reshape([temp(2:end-2) temp(end)],2,[]);
spmd(NSLOTS)
	partial_tot = 0;
	for i=chunk(1,labindex):chunk(2,labindex)
        partial_tot = partial_tot + i;
    end
    disp(partial_tot)
end

disp(partial_tot{1}+partial_tot{2}+partial_tot{3}+partial_tot{4})