MATLAB: When starting local workers can I specify an affinity mask for each worker in Parallel Computing Toolbox R2013b

Parallel Computing Toolbox

When starting local workers, for example by opening a MATLABPOOL or PARPOOL, I want to specifically assign each worker to a specific core on my system. Is it possible to do this?

Best Answer

The ability to automatically change the affinity mask for local workers is not available in Parallel Computing Toolbox R2013b. 
On Windows in general it is possible however to change the affinity mask of a process by calling the SetProcessAffinityMask Windows API function; in MATLAB you could do this from a MEX-file; an example MEX-file is attached to this article. You will need to compile the MEX-file using the MEX function. Once the file has been compiled you should be able to use something like the following to assign an unique core to each worker:
% Open the pool
matlabpool open local
% On all workers run the SetAffinity function
spmd
SetAffinity(uint64(2^(labindex-1)))
end
% Your own PARFOR/SPMD code goes here
% Clean-up/close
matlabpool close
On Linux you could use the taskset command which can be called through the SYSTEM function. Basically you can use the same approach as above only instead of calling SetAffinity you could use something like:
system(sprintf('taskset -p %d %d',2^(labindex-1),feature('getpid')))
*Important Note *when working with Intel CPUs with Hyperthreading enabled, you will only want to assign your workers to physical cores and not the logical hyperthreading cores. This means you will need to make some changes to how you compute the masks for the workers..