Matlab onCleanup function not executed -
i ran following issue in matlab r2013a, reason not understand not call oncleanup function when in function timer (including timerfcn) defined.
i add 2 minimal examples showing problem:
first working version cleanup routine called expected:
function mytest(time) t = timer(); myclean = oncleanup(@() disp('function ended')); pause(time); end
and buggy version in cleanup not called (neither when function ends or when ctrl+c pressed)
function mytest2(time) t = timer(); t.timerfcn = @(o,s)disp(' ... waiting time'); myclean = oncleanup(@() disp('function ends')); pause(time); end
i not find hints in documentation why timer or more specific definition of timerfcn change execution of cleanup code?
ouch - nasty. it's not bug, it's not you'd expect documentation, , it's not you'd want. fortunately it's pretty easy work around.
firstly, what's happening?
well, oncleanup
returns oncleanup object. object sole purpose have destructor method set @() disp('function ends')
. when object goes out of scope (which expect @ end of function mytest2
), gets deleted, destructor method executes, , message gets displayed. that's expect, think.
but when create anonymous function @(o,s)disp(' ... waiting time')
, , assign timerfcn
of timer, takes copy of entire current workspace of function mytest2
, including oncleanup
object. timer created in base workspace (not function workspace), , remains in existence @ end of function, along oncleanup
object, never goes out of scope, never gets deleted, destructor function never runs, , don't message.
note that:
- if run
a = timerfindall; delete(a);
in base workspace, message, you've explicitly deleted timer alongoncleanup
object. - this behaviour anonymous functions taking copy of entire workspace documented, although may not aware of it, , although don't want work here. it's nasty.
fortunately, it's easy work around:
function mytest3(time) t = timer(); settimerfcn(t) myclean = oncleanup(@() disp('function ends')); pause(time); end function settimerfcn(t) t.timerfcn = @(o,s)disp(' ... waiting time'); end
now, when anonymous function created takes copy of local workspace (i.e. subfunction settimerfcn
), not include oncleanup
object. oncleanup
object goes out of scope @ point expect to, , everything's fine.
hope helps!
Comments
Post a Comment