필터 지우기
필터 지우기

Running functions in parallel

조회 수: 1 (최근 30일)
Andrea Carroll
Andrea Carroll 2020년 2월 4일
답변: Edric Ellis 2020년 2월 5일
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

답변 (1개)

Edric Ellis
Edric Ellis 2020년 2월 5일
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);

카테고리

Help CenterFile Exchange에서 Parallel Computing Fundamentals에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by