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

 Réponse acceptée

Catalytic
Catalytic il y a environ 24 heures
Modifié(e) : Catalytic il y a environ 24 heures
If you use a process-based pool, it will work --
parpool('Processes')

Plus de réponses (1)

Matt J
Matt J il y a environ 23 heures
Modifié(e) : Matt J il y a environ 22 heures
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

1 commentaire

Jake
Jake il y a environ 8 heures
Thanks, I think this level of burying removes a lot of the benefits of argument validation for me (CLI completion, code clarity). But, it's nice to know such a solution is possible

Connectez-vous pour commenter.

Catégories

Produits

Version

R2023b

Question posée :

le 19 Mai 2026 à 13:35

Commenté :

il y a environ 8 heures

Community Treasure Hunt

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

Start Hunting!

Translated by