Running functions in parallel

2 visualizaciones (últimos 30 días)
Andrea Carroll
Andrea Carroll el 4 de Feb. de 2020
Respondida: Edric Ellis el 5 de Feb. de 2020
clc;
pause on
tic;
parpool(2);
f1 = parfeval(@Function_I, 1);
f2 = parfeval(@Function_II, 1);
function1=Function_I();
function2=Function_II();
delete(gcp('nocreate'));
function func1 = Function_I()
disp('Starting function 1:');
startF1=toc
a=5;
b=6;
func1=a*b;
pause(0.1);
disp('End function 1:');
EndF1=toc
end
function func2 = Function_II()
disp('Starting function 2:');
StartF2=toc
a=4;
b=6;
func2=a*b;
pause(0.1);
disp('End function 2:');
EndF2=toc
Command Window displays;
>>
Starting parallel pool (parpool) using the 'local' profile ...
Connected to the parallel pool (number of workers: 2).
Starting function 1:
startF1 =
15.9759
End function 1:
EndF1 =
16.0768
Starting function 2:
StartF2 =
16.0772
End function 2:
EndF2 =
16.1776
Parallel pool using the 'local' profile is shutting down.
>>
Clearly Function_I is executed before Function_II. Does anyone know how I can make these two functions run at the same time. I have tired using 'parpool' but this does not seem to work

Respuestas (1)

Edric Ellis
Edric Ellis el 5 de Feb. de 2020
In your code above, the two parfeval lines are initiating asynchronous function evaluation requests in parallel. You're also calling Function_I and Function_II directly in the client session on the subsequent lines, and that's what's being printed out in the command window. I suggest removing those two lines (i.e. function1=Function_I();), and instead add the following after the parfeval lines:
wait(f1); wait(f2); % Wait for parallel execution to complete
f1.Diary % Display the command-window output from the execution of Function_I
f2.Diary % ... and Function_II
You can also get the results using
result_1 = fetchOutputs(f1);
result_2 = fetchOutputs(f2);

Categorías

Más información sobre Parallel Computing Fundamentals en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by