Possible Duplicate:
How do you handle resources in MATLAB in an exception safe manner? (like “try … finally”)
I use Matlab parallel computing toolbox this way:
matlabpool open
parfor …
matlabpool close
If error occurs in parfor
, the program is terminated, and matlabpool is not closed. When I fix the bug and run it again, matlabpool open
fails because it is already open. So I need to close it manually, which I always forget. The ideal way would be to change it to (pseudo-code):
matlabpool open
try
parfor …
finally
matlabpool close
end
Is there any best practice for this?
If you use try and catch , this code catches any exception and repackages it as a warning, allowing MATLAB to continue executing subsequent commands.
Select MATLAB > Code Analyzer, and then select the Enable integrated warning and error messages check box. Set the Underlining option to Underline warnings and errors . When continuous code checking is enabled, MATLAB displays warning and error messages about your code in the Editor and Live Editor.
Use onCleanup
. It'll let you set up code that'll get executed when you exit the scope, regardless of a normal or a error exit. So it works like finally, plus it quashes exceptions in the cleanup, and all onCleanup
s are independent.
function doSomething
matlabpool open
cleaner = onCleanup(@() matlabpool('close'));
parfor ...
%// and then no need to call close here
You need to change the try...finally
to a function, or stick it inside one, for this to work right. The cleanup code only gets executed with the GC clears the contents of cleaner
, which happens when its workspace goes out of scope when you leave the function (or when you manually clear it). Unlike some other languages, Matlab's try
block is not a lexical scope for variables; variables assigned for the first time inside a try
will stick around until their enclosing function is left. Same for all other blocks: the function is the only level of scoping for local variable lifetimes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With