Matlab timer is not executed asynchronously
Show older comments
Hi, I am developing a Matlab UI program where the callback of a button pressed might take lots of time to process. So I basically want the callback to be executed asynchronously and ask the UI to update the callback result when it is ready.
Some documents suggests doing this by using Matlab timer callback but I found the callback is still not executed asynchronously.
Here is a simple code for testing:
function [ ] = ThreadTest( )
t = timer('StartDelay',0.1, 'TimerFcn',@utilityFcn);
start(t);
for i=1:10000;
pause(0.1);
fprintf('x');
end
end
function utilityFcn(src,evt)
% some lengthy calculation/update done here
for i=1:100;
temp = rand(1000,1000)*rand(1000,1000);
end
fprintf('done');
end
I expect this program will continuously print 'x' in every 0.1 sec and there will be a print of 'done' when the callback is finished. However, in this example, the 'x' is only printed when the all lengthy computation is done (i.e., always printed after the 'done' is printed)
Accepted Answer
More Answers (1)
Note what would happen, if the timer would be asynchronous:
function [ ] = ThreadTest( )
global x
t = timer('StartDelay', 1, 'TimerFcn', @utilityFcn);
start(t);
for i = 1:100;
pause(0.1);
x = x + 1;
fprintf('%d ', x);
end
end
function utilityFcn(src,evt)
global x
x = x + 1000;
end
Now there would be a racing condition between the main thread and the timer callback: The main thread gets the value of x and increases it by 1. If now the timer thread does exactly the same, it is not predictable which thread writes back the new value at first.
Unpredictable states are extremely bad for programming. And therefore Matlab is single threaded currently. [EDITED: added] This means that there cannot run code asynchronously, neither as a timer callback nor by using C-Mex tricks like mexCallMATLAB from several threads.
But what about parfor loops? [EDITED end]
The example might look artifical, but the real world code is much more complicated and collisions are harder to find, but this does not mean that they do not occur. It can concern persistent variables, ApplicationData of GUI objects, the state of mutual exclusive radio buttons, writing to files, etc.
2 Comments
Yu-Chih Tung
on 29 Mar 2017
@Yu-Chih Tung: Matlab is single-threaded. You cannot run code asynchronusly. If you try this using tricks in the MEX interface, Matlab crashs as expected.
So my answer is: This will not work. Matlab is not prepared to handle e.g. the mentioned racing conditions in its internal functions.
parfor loops run asynchronously. I do not have teh parallel processing toolbox, so wait if anybody else posts a corresponding solution.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!