image thumbnail

Worker Object Wrapper

version (3.39 KB) by MathWorks Parallel Computing Toolbox Team
Simplifies managing resources such as large data within PARFOR loops and SPMD blocks


Updated 31 Oct 2016

View License

Editor's Note: This file was selected as MATLAB Central Pick of the Week

Note that since MATLAB release R2015b, parallel.pool.Constant supersedes
the WorkerObjWrapper.
The WorkerObjWrapper is designed for situations where a piece of
data is needed multiple times inside the body of a PARFOR loop or
an SPMD block, and this piece of data is both expensive to
create, and does not need to be re-created multiple
times. Examples might include: database connection handles, large
arrays, and so on.
Consider a situation where each worker needs access to a large
but constant set of data. While this data set can be passed in to
the body of a PARFOR block, it does not persist there, and will
be transferred to each worker for each PARFOR block. For example:

largeData = generateLargeData( 5000 );
parfor ii = 1:20
x(ii) = someFcn( largeData );
parfor ii = 1:20
y(ii) = someFcn( largeData, x(ii) );

This could be simplified like so:

wrapper = WorkerObjWrapper( @generateLargeData, 5000 );
parfor ii = 1:20
x(ii) = someFcn( wrapper.Value );
parfor ii = 1:20
y(ii) = someFcn( wrapper.Value, x(ii) );

In that case, the function "generateLargeData" is evaluated only
once on each worker, and no large data is transferred from the
client to the workers. The large data is cleared from the workers
when the variable "wrapper" goes out of scope or is cleared on
the client.

Another example might be constructing a worker-specific
log-file. This can be achieved like so:

% build a function handle to open a numbered text file:
fcn = @() fopen( sprintf( 'worker_%d.txt', labindex ), 'wt' );

% opens the file handle on each worker, specifying that fclose
% will be used later to "clean up" the file handle created.
w = WorkerObjWrapper( fcn, {}, @fclose );

% Run a parfor loop, logging to disk which worker operated on which
% loop iterates
parfor ii=1:10
fprintf( w.Value, '%d\n', ii );

clear w; % causes "fclose(w.Value)" to be invoked on the workers
type worker_1.txt % see which iterates worker 1 got

Cite As

MathWorks Parallel Computing Toolbox Team (2021). Worker Object Wrapper (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2013b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!