Code covered by the BSD License  

Highlights from
Worker Object Wrapper

5.0

5.0 | 1 rating Rate this file 8 Downloads (last 30 days) File Size: 3.13 KB File ID: #31972

Worker Object Wrapper

by Edric Ellis

 

27 Jun 2011

Simplifies managing resources such as large data within PARFOR loops and SPMD blocks

| Watch this File

File Information
Description

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 );
end
parfor ii = 1:20
  y(ii) = someFcn( largeData, x(ii) );
end

This could be simplified like so:

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

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 );
end

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

Required Products Parallel Computing Toolbox
MATLAB release MATLAB 7.12 (2011a)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (1)
03 Nov 2011 Christopher Kanan  
Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
parallel computing Edric Ellis 13 Jul 2011 11:18:05
parfor Edric Ellis 13 Jul 2011 11:18:05

Contact us at files@mathworks.com