Running functions in parallel
2 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Edric Ellis
on 5 Feb 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);
0 Comments
See Also
Categories
Find more on Parallel Computing Fundamentals in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!