matlab - Execute 3 functions in parallel on 3 workers -
i've got 3 functions (qrcalc
, zcalc
, pcalc
) 3 unique set of inputs want run in parallel. attempt doesn't work:
function [outall]=parallelfunc(in1,in2,in3) if parpool('size') == 0 % checking see if pool open a=feature('numcores'); parpool('local',a); else parpool close a=feature('numcores'); parpool('local',a); end spmd if labindex==2 out1=qrcalc(in1); elseif labindex==3 out2=zcalc(in2); elseif labindex==4 out3=pcalc(in3); end outall=[out1;out2;out3]; end
error: error using parallelattempt>(spmd body) (line 20) error detected on worker 3. undefinedfunction error thrown on workers 'out1'. may because file containing 'out1' not accessible on workers. specify required files parallel pool using command: addattachedfiles(pool, ...). see documentation parpool more details.
error in parallelattempt>(spmd) (line 11) spmd
error in parallelattempt (line 11) spmd
are there suggestions how can done?
here version of code not require custom functions. therefore replaced them zeros
, magic
, ones
:
function [outall]=parallelattempt(in1,in2,in3) poolobj = gcp; addattachedfiles(poolobj,{'zeros.m','ones.m','magic.m'}) spmd if labindex==2 out1=zeros(in1); elseif labindex==3 out2=magic(in2); elseif labindex==4 out3=ones(in3); end outall=[out1;out2;out3]; end
if use spmd
-statement, code inside sent workers. use of labindex
create variables outx
on 1 specific worker. problem is, outall=[out1;out2;out3];
should executed on workers 2 outx
-variables not declared. direct fix error declare variables before spmd
-statement (out1=[]; out2=[]; out3=[];
). not best solution.
you can use single variable inside spmd
-statement instead of several ones (outx
), lets call variable out
. code executes on each worker , stores result in out
, composite
-object. concatenation not necessary because done automatically. additionally, can specify spmd (3)
@ beginning of block 3 workers should used. composite
-objects can indexed cell arrays index equals number of worker/lab. therefore can concatenate after block.
this specific code part:
spmd (3) if labindex==1 out = qrcalc(in1); elseif labindex==2 out = zcalc(in2); elseif labindex==3 out = pcalc(in3); end end outall = [out{1};out{2};out{3}];
note creation of pool done automatically, if none exists. may need attach files of functions before statement.
an better approach in opinion use parfeval
here. want achieve in first place - solves initial problem. outx
variables calculated in parallel (non-blocking). function fetchoutputs
can block execution until result calculated. use on outx
-variables , concatenate in same line.
here code that:
out1 = parfeval(@qrcalc,1,in1); out2 = parfeval(@zcalc,1,in2); out3 = parfeval(@pcalc,1,in3); outall = [fetchoutputs(out1);fetchoutputs(out2);fetchoutputs(out3)];
Comments
Post a Comment