11

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?

Community
  • 1
  • 1
Roman Shapovalov
  • 2,785
  • 27
  • 30
  • 1
    I agree; dup. The other was harder to find in search though. I fussed with its title so it'd show up in a search for "matlab finally". – Andrew Janke Jan 26 '12 at 21:29

1 Answers1

20

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 onCleanups 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.

Andrew Janke
  • 23,143
  • 5
  • 55
  • 84