필터 지우기
필터 지우기

Am I running in parallel? (best way to check)

조회 수: 38 (최근 30일)
Felipe G. Nievinski
Felipe G. Nievinski 2013년 1월 8일
댓글: Roman Krylov 2023년 6월 6일
Is there a better way than this?
function answer = is_in_parallel ()
try
answer = ~isempty(getCurrentTask());
catch err
if ~strcmp(err.identifier, 'MATLAB:UndefinedFunction')
rethrow(err);
end
answer = false;
end
end
  댓글 수: 8
Felipe G. Nievinski
Felipe G. Nievinski 2013년 1월 8일
Other possibilities that I considered for checking were:
~isempty(ver('distcomp'))
and:
(matlabpool('size') > 0)
but neither seemed better than:
~isempty(getCurrentTask())
Tom Holden
Tom Holden 2022년 4월 8일
getCurrentTask throws an error within a thread based parallel pool. So perhaps answer should be true if an error is thrown!

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2013년 1월 9일
Let me summarize the current discussion:
No. There seems to be no better solution.

추가 답변 (3개)

埃博拉酱
埃博拉酱 2023년 4월 3일
편집: 埃博拉酱 2023년 4월 3일
parallel.internal.pool.isPoolThreadWorker||~isempty(getCurrentJob))
This code can robustly return true if and only if run on a parallel worker either as threads or processes.

Tom Holden
Tom Holden 2022년 4월 8일
~usejava( 'desktop' ) seems to work even on thread based parallel pools.

Daniel Shub
Daniel Shub 2013년 1월 9일
MATLAB has a number of such functions that tell you about the state of the world (e.g., ispc, isdeployed, isjava). These functions seem to be necessary since there are thing you can/cannot do when they are true/false. I am not sure that something like isparallel is needed. It seems you are looking for something more like isheadless. That said, I am not sure this is the best approach. I am guessing here, but it sounds like your two uses cases are something like
parfor = 1:N
myFuncThatComputesAndPrints;
end
and
for = 1:N
myFuncThatComputesAndPrints;
end
and you want myFuncThatComputesAndPrints to know if it is running headless so that it will suppress the printing. I would suggest that you modify myFuncThatComputesAndPrints to take a flag to determine if it should print giving you
printFlag = true;
parfor = 1:N
myFuncThatComputesAndPrints(printFlag);
end
myFuncThatOnlyPrints;
and
printFlag = false;
for = 1:N
myFuncThatComputesAndPrints(printFlag);
end
This would allow you to expand the cases where you choose not to print.
  댓글 수: 5
Felipe
Felipe 2013년 1월 9일
How would you implement isparallel that would work if called outside the parfor? I don't think any of ~isempty(ver('distcomp')), (matlabpool('size') > 0), or ~isempty(getCurrentTask()) would work.
Jan
Jan 2013년 1월 9일
getCurrentTask() works outside a PARFOR loop and replies [].

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by