MATLAB: How to update a property of an object of a class with GUI, multi-threading, I presume

guimultiprocessingoop

I'm calling the print_num class from a GUI.
classdef print_num
properties (SetAccess = private)
flag = 0;
n;
end
methods
function obj = print_all(obj, n)
%PRINT_ALL Prints numbers until interupted
obj.flag=0
obj.n = n
disp('print_num function')
i=1
while i<=obj.n
if obj.flag == false
fprintf('%i flag: %i\n', i, flag)
pause(0.1)
i=i+1;
else
break
end
end
end
function obj = stop(obj)
%STOP Stop printing of numbers
disp('Stop function')
obj.flag=1
end
end
end
I need want to stop the printing of numbers when stop() method is called. I'm calling both the methods print_all(n) and stop() from two pushbuttons of a GUI.
function multiprocessing_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
handles.p = print_num;
guidata(hObject, handles);
% --- Executes on button press in f1.
function f1_Callback(hObject, eventdata, handles)
handles.p = handles.p.print_all(20);
guidata(hObject, handles);
% --- Executes on button press in f2.
function f2_Callback(hObject, eventdata, handles)
disp('stop called')
handles.p = handles.p.stop();
guidata(hObject, handles);
I'm unable to stop the printing of numbers with the flag property of the class print_num. Can someone explain me what I'm doing wrong?

Best Answer

Neel - try deriving your print_num class from the handle class as
classdef print_num < handle
This will make sure that your obj objects are references to the (same) instantiated object.
Also, rather than using a while loop, you may want to consider using a timer to perform the iterative action. For example,
classdef print_num < handle
properties (SetAccess = private)
m_n;
m_timer = [];
m_iter;
end
methods
function obj = print_num()
m_n = 0;
m_timer = [];
m_iter = 0;
end
function obj = print_all(obj, n)
if isempty(obj.m_timer)
obj.m_timer = timer('Name','MyTimer', ...
'Period',0.1, ...
'StartDelay',0, ...
'TasksToExecute',inf, ...
'ExecutionMode','fixedSpacing', ...
'TimerFcn',{@print_num.myTimerCallback, obj});
obj.m_n = n;
obj.m_iter = 1;
start(obj.m_timer);
end
end
function obj = stop(obj)
if ~isempty(obj.m_timer)
stop(obj.m_timer);
obj.m_timer = [];
end
end
end
methods (Static)
function myTimerCallback(hTimer, event, objRef)
fprintf('obj.m_iter = %d\n', objRef.m_iter);
objRef.m_iter = objRef.m_iter + 1;
end
end
end