Graphics argument validation for function in parfor loop
이전 댓글 표시
I have a function that I'd like to run serially but also sometimes inside a parfor loop, with the ability to optionally plot output. Understandably, I can't plot or modify graphics within a parpool thread, but I find even having unused relevant argument validation that draws from matlab.graphics.axis.Axes class properties causes a parallel:threadpool:NonConcurrentLibrary error to be thrown during parallel execution. Attached is a code snippet demonstrating what I mean.
I suppose I have two questions. First, is this expected behaviour, given that args is not even invoked in the body of the function? Second, is there any way to retain automatic argument validation for an axis object that plays nicely with parfor, in cases where these arguments are used conditionally and never during parallel execution?
function ArgValidationParForTest()
pool = gcp();
fprintf('Parallel pool initialised with %d workers\n', pool.NumWorkers)
ntests = 10;
parfor i = 1:ntests
TestFunc()
end
end
function TestFunc(args)
arguments
args.?matlab.graphics.axis.Axes
end
fprintf('Called\n')
end
채택된 답변
추가 답변 (1개)
Second, is there any way to retain automatic argument validation for an axis object that plays nicely with parfor, in cases where these arguments are used conditionally and never during parallel execution?
You would probably have to hand off to a separate validation routine,
function TestFunc(varargin)
fprintf('Called\n')
args=handOff(varargin{:});
end
function args=handOff(varargin)
p = gcp('nocreate');
args=[];
if isempty(p) || ~isa(p,'parallel.ThreadPool')
args=validateGraphics(varargin{:});
elseif ~isempty(varargin)
error 'Handle graphics aren''t supported in threadpools'
end
end
function args=validateGraphics(args)
arguments
args.?matlab.graphics.axis.Axes
end
end
댓글 수: 2
Jake
2026년 5월 20일 8:46
You can recover some of the benefits of CLI by adding an explicit argument list, i.e., by copy-pasting the following auto-generated argument list into your TestFunc arguments block. This block knows only the names of the name/value parameters, and not any of the defaut values and type restrictions. So you would still need to use the handOff function to do the validation proper. However, it at least it will complete the parameter names for you.
disp(char( " args."+properties("matlab.graphics.axis.Axes") ))
카테고리
도움말 센터 및 File Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!