onCleanup and script

Hello.
I'm using a parfor loop,but sometimes I stop its execution with ctrl+c, so I would like to execute the command "matlabpool close" immediately in order not to leave the processes on. I have recommended to use onCleanup function,but I have read that I need to use it within a function and not in a script, and I've got a script, owe to that fact I wonder if I could do the same with a try/catch sentence, is it possible?
thanks!

 Respuesta aceptada

Walter Roberson
Walter Roberson el 27 de Jul. de 2011

0 votos

No. try/catch cannot catch a control-c .
I would suggest just converting your script in to a function: doing so is likely to be far easier than working around the issue.

4 comentarios

Javier
Javier el 27 de Jul. de 2011
So the structure of the code would be:
function
matlabpool 3;
...
whatever
...
c=onCleanup(@()liberaRecursos(gE));
end
end
function r=liberaRecursos(gE)
matlabpool close;
r=1;
end
Walter Roberson
Walter Roberson el 27 de Jul. de 2011
Well, you would need an actual function name at the beginning (which must match the name of the file.)
Your cleanup routine does not need to return a value, so you could use
c = onCleanup(@() matlabpool('close'));
and you should define this early on, probably just after you open the pool.
Javier
Javier el 27 de Jul. de 2011
does the function onCleanup only work locally?
Walter Roberson
Walter Roberson el 27 de Jul. de 2011
The onCleanup function is invoked when the object it returns ("c" in this case) goes out of scope and is destroyed. Normally that happens when the workspace of the function is cleaned up in preparation for returning from the function, but if the object were to be returned or written in to a global or persistent variable, it might get delayed.
onCleanup runs whatever function it is handed. Note that that is _function_: you do not pass it a reference to a particular variable or object.

Iniciar sesión para comentar.

Más respuestas (1)

Javier
Javier el 27 de Jul. de 2011

0 votos

I'm having got a problem, I have done what I told you, adding a name to the function but, it doesn't work rightly in that in matlab prompt does not appear the message "Sending a stop signal..."
I should set the instruction just before the last "end" of the function, shouldn't I?

1 comentario

Walter Roberson
Walter Roberson el 27 de Jul. de 2011
onCleanup() should go just after you have created the conditions that need to be cleaned up later -- e.g., just after you have opened the pool.

Iniciar sesión para comentar.

Categorías

Más información sobre Scope Variables and Generate Names en Centro de ayuda y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by