- Undocumented Matlab - https://undocumentedmatlab.com -

Waiting for asynchronous events

Posted By Yair Altman On July 18, 2012 | 33 Comments

It often happens that we need our program to wait for some condition to occur. This condition may depend on some external process that updates the condition asynchronously, meaning in a non-predictable (non-specific) time. A typical example is user mouse or keyboard actions in a GUI dialog window, or a specific signal that is received from hardware.

waitfor and other built-in functions

Matlab has a couple of built-in functions for blocking Matlab’s main processing thread until certain asynchronous GUI events occurs. waitfor is documented to block code execution until either the specified GUI handle object is deleted, or is updated (possibly to a specified value), or Ctrl-C is pressed in matlab’s Command Window. uiwait similarly blocks execution, until a specified figure handle is deleted/closed, or a separate processing thread (typically, a callback function) calls the corresponding uiresume (I discussed [1] uiwait/uiresume, together with their uisuspend/uirestore siblings, last year). uiwait, unlike waitfor, has an optional timeout parameter; on the other hand, uiwait cannot wait for a non-deletion event on a regular uicontrol property, as waitfor can.
Other related built-in Matlab functions are waitforbuttonpress, pause (which awaits user mouse/keyboard clicks), and ginput, gtext, rbbox, dragrect (which awaits mouse clicks in a plot/image axes). Some toolboxes have other similar blocking functions, for example roipoly in the Image Processing toolbox.

Waiting for events on non-HG objects

But what if we need to wait for an event to happen on a non-Matlab (HG) object? Say on an ActiveX control property or even on a non-graphical Java object?
It turns out that waitfor can also be used in these cases. Although not documented, waitfor actually accepts handles not only of HG objects (e.g., figure handles) but also of other types of handles, such as regular Java reference handles. The usage is the same as for regular HG handles:

waitfor(objectHandleOrReference, 'propertyName', propertyValue);

For example, to wait for data to be available in a java.util.Hashtable object, which has a public boolean isEmpty() method and therefore returns a value of ‘on’ or ‘off’ for get(object,’Empty’):

waitfor(javaHashTableReference, 'Empty', 'off');


(Note that Matlab automatically converts a Java boolean into ‘on’/’off’ in such cases, so we need to use ‘on’/’off’ rather than true/false; this is not always the case – a counter-case is presented immediately below)

Setting a timeout on waitfor

To set a timeout on our blocked wait, a feature of uiwait that is missing in the built-in waitfor, we can use a dedicated one-time timer object. Timer callbacks use a separate thread from the main Matlab processing thread, and are therefore processed even when the Main thread is blocked. The implementation is quite easy, as shown below:

% Wait for data updates to complete (isDone = false if timeout, true if data ok)
function isDone = waitForDone(object,timeout)
    % Initialize: timeout flag = false
    object.setDone(false);
    % Create and start the separate timeout timer thread
    hTimer = timer('TimerFcn',@(h,e)object.setDone(true), 'StartDelay',timeout);
    start(hTimer);
    % Wait for the object property to change or for timeout, whichever comes first
    waitfor(object,'Done',true);
    % waitfor is over - either because of timeout or because the data changed
    % To determine which, check whether the timer callback was activated
    isDone = (hTimer.TasksExecuted == 0);
    % Delete the time object
    try stop(hTimer);   catch, end
    try delete(hTimer); catch, end
    % Return the flag indicating whether or not timeout was reached
end  % waitForDone

Polling

In some cases (for example, waiting on a specific field value within a struct, which waitfor does not support), we need to revert to using plain-ol’ polling, rather than the more efficient blocked wait. In such cases, I strongly advice to place a certain pause within the polling loop:

delay = 0.01;  % 10 milliseconds
while ~object.isDone  % set by the callback
    pause(delay);  % a slight pause to let all the data gather
end

Or, a variant with timeout:

delay = 0.01;
for idx = 1 : (timeout/delay)  % wait up to N secs before giving up
    if object.isDone  % set by the callback
        break;
    end
    pause(delay);  % a slight pause to let all the data gather
end

The reason we need this deliberate pause is to enable the CPU to process other processing threads, namely that thread which is responsible for updating the field value in due time. Without this pause, it would take the CPU much longer (if at all) to get to that thread, and our overall application performance will actually degrade, since the event will take longer to get processed.
Adding deliberate pause delays as a mechanism to improve overall performance may sound counter-intuitive, but this is in fact the case here. Performance tuning can indeed be counter-intuitive sometimes, until you learn the underlying reasons when it becomes clear (I’ve shown several examples of this in the past, here [2], here [3], here [4] and here [5]).
We should take care not to set too high a pause delay, since that will unnecessarily delay processing of the incoming event; on the other hand, setting it too low will return the thread-starvation issue explained above. A pause value of 5-50 millisecs (0.005-0.05) should be about right for the vast majority of applications. Note that different platforms run your application at different speeds, so be careful not to over-tune this delay to a particular computer.
Interested in learning more Matlab performance or advanced programming tricks? Then consider joining my Matlab Performance Tuning [6], Advanced Matlab GUI [7] and/or Matlab-Java programming [8] seminars in Geneva on August 21-23, 2012 – email me [9] (altmany at gmail dot com) for details.

Categories: GUI, High risk of breaking in future versions, Java, Listeners, Stock Matlab function, Undocumented feature


33 Comments (Open | Close)

33 Comments To "Waiting for asynchronous events"

#1 Comment By Brad Stiritz On July 21, 2012 @ 08:24

Hi Yair,

Thanks for your post, very interesting.

It seems like conceptually, one could create an effectively multi-threaded MATLAB application using the ideas in your posting & the MATLAB compiler. Each thread would be deployed as a separate process & messages / event info would be passed between the processes via a robust message broker, e.g Java GlassFish.

I’m also thinking it might be possible to take this idea one step further, via the Parallel Computing Toolbox. Worker threads could be programmed to immediately go into async “stand-by”, per your post, & then be controlled via the message architecture. This would cut out the PCT set-up/retrieval overhead, which over hundreds of parallel jobs could be significant.

Have you ever worked on or heard of any MATLAB projects where something like this has been done successfully? It seems pretty straightforward, doesn’t it? Do you have any experience using MATLAB & GlassFish together? If so, how did things go?

Any comments appreciated,
Thanks,
Brad

p.s. I wasn’t able to get the HTML carriage return tag “br” or the paragraph break tag “p” to work in my comment. Could you please advise on how to achieve paragraph breaks?

#2 Comment By Yair Altman On July 21, 2012 @ 10:38

@Brad – thanks. I haven’t used GlassFish before. What you suggested sounds reasonable on first read, but I have never attempted such inter-process Matlab communications. I do know that Matlab IPC has been attempted by others, though. There are even several such mechanisms on the File Exchange, although I don’t know whether they use an efficient async mechanism or inefficient polling.

Re para break, simply press the ENTER key twice – this will automatically create the paragraph break that you were looking for, just as in you own comment.

#3 Comment By Alex On July 26, 2012 @ 02:56

Is it possible to set a timeout for a calculation? I’m calling an external function that doesn’t always converge, so it is possible that MATLAB stays busy forever when I call the function. I want to do something like this:

try(timeout = 60)
external_fun;
catch ME
error('Function did not converge in 60 seconds')
end

#4 Comment By Yair Altman On July 26, 2012 @ 02:59

@Alex – no, but you could add a check for the timeout condition in your calculation function (in its main loop for example), if you can modify its source code.

#5 Comment By Brad Stiritz On July 28, 2012 @ 14:31

Yair,

Thanks for your reply. Looking at the MATLAB MCR documentation, it says:

“The MCR makes use of thread locking so that only one thread is allowed to access the MCR at a time. As a result, calls into the MCR are threadsafe for MATLAB Compiler generated libraries, COM objects, and .NET objects. On the other hand, this can impact performance.”

Do you think this also means that only one *process* is allowed to access the MCR at a time? If so, then wouldn’t this effectively preclude multiple deployed apps from running at the same time? That doesn’t seem right, though, does it?

#6 Comment By Yair Altman On July 29, 2012 @ 02:08

@Brad – I do not have any additional information on this. It should be simple enough to test, and you could always ask MathWorks support about this.

#7 Comment By Tomás Peyré On August 27, 2012 @ 01:08

Yair,
I’ve doing data polling from a sensor with Matlab’s pause command in the loop for some time.
My application was leaking memory and would crash after several hours.
Matlab support confirmed they have a memory leak issue when calling pause within a loop on R2011b and R2012a.

Inspired in your use of Java native functions, I wrote this alternative pause function that solve the problem for me and may help others:

 
function pauseJava(tPauseSec)
	th = java.lang.Thread.currentThread();  %Get current Thread
	th.sleep(1000*tPauseSec)                %Pause thread, conversion to milliseconds

#8 Comment By Yair Altman On August 27, 2012 @ 02:25

@Tomás – thanks for the information and the workaround 🙂

#9 Pingback By Pause for the better | Undocumented Matlab On August 29, 2012 @ 11:02

[…] A few days ago, blog reader Tomás Peyré commented on the fact that the pause function has a memory leak on R2011b and R2012a […]

#10 Comment By Jim Hokanson On August 29, 2012 @ 14:00

Hi Yair,

Any ideas on how to accomplish what you describe above with Matlab objects? I tried passing in a handle class object and Matlab didn’t like it.

Thanks,
Jim

#11 Pingback By Take a break, have a pause() | matlabideas On May 18, 2013 @ 08:34

[…] pause() has a memory leak […]

#12 Comment By Rafael On May 30, 2013 @ 09:58

Yair, this web site is an incredible resource. Thank you!!

A long time ago I created code that has loops like the one you show here to wait for asynchronous events. But it never works well. All of the testing I have done indicates that no other threads are executed when Matlab executes a pause command. The wait loop never receives the event, because the thread that is supposed to create the event never gets executed while the wait loop is running. Are you sure Matlab does allow other threads to run while a pause is executing?

Thanks!

#13 Comment By Bolivar On July 31, 2013 @ 10:52

do waitfor only take java object as arguments or matlab object reference as well? If so which package should i add to be able to implement the the waitForDone function described above?

Thanks for your support!

#14 Comment By Yair Altman On July 31, 2013 @ 11:10

@Bolivar – waitfor also accepts Matlab handles. See [16]. There is no need for any external package to use waitForDone.

#15 Comment By Bolivr Djamen On October 14, 2013 @ 12:31

Thanks Yair , according to your reference it seem like just Graphic object can be given as argument to waitfor! actually I want to use it with common handle object defined with key word classdef

#16 Comment By Yair Altman On October 16, 2013 @ 11:00

I’m not sure that this is supported, but you are welcome to try. Please let us all know if it works for you.

#17 Comment By Daniel R On May 18, 2014 @ 16:39

Hi Yair,
I have a main GUI that calls several secondary GUIs and I’m using the uiwait function to hold the main window active but it disables the functionality of the command window and disables any other plots that i generate while its running for editing.

I was wondering if you know of any way that the MATLAB command window can still be used while the uiwait function is being used to work with multiple GUI windows?

#18 Comment By Yair Altman On May 18, 2014 @ 17:03

@Daniel – no. You need to find an alternative to uiwait in your program if you need console interactivity. uiwait is designed for modality and what you request is not purely modal.

#19 Comment By Jan On January 7, 2015 @ 08:49

Hi,
the method that you proposed in the “Waiting for events on non-HG objects” does not seem to work anymore (2014b)
I now get the following error:

 
Error using waitfor
Parameter must be scalar.

Can you confirm that this is indeed a problem in newer versions?

Thanks
Jan

#20 Comment By Jan On January 9, 2015 @ 03:27

I experimented a little bit.

my goal is to block matlab execution until something in the java environment happens.
for this i set a value in the java class to true. in an internal callback, this value changes to false
if I pass my java class to the waitfor function like this:

eventTest.setStartBlocked(true);
waitfor(eventTest,'StartBlocked','off')

I get the following error message

Error using waitfor
Conversion to double from name.of.class is not possible.

The error message I posted earlier occurs if I wrap my class with the handle command.

waitfor will still wait for a figure, so maybe an ugly workaround would be using an invisible figure in some way?

Maybe you have some better ideas

#21 Comment By William On December 1, 2015 @ 07:18

About a year later, I second what Jan said. Matlab no longer allows non-scalar(able) objects passed into waitfor.

I think you should update this article with a disclaimer that later versions of Matlab no longer support this behavior.

#22 Comment By Peter On January 8, 2016 @ 10:01

Hi Yair,

Is there a way to create a MATLAB function which works similar to waitforbuttonpress, except that it does not depend on a figure?

I’m looking for a way for MATLAB to detect a mouse left-click anywhere on screen (not only inside a MATLAB figure or window).

#23 Comment By Marc Passy On January 20, 2016 @ 22:49

Just a detailed point – waitfor now (as of 2015a) throws this error when using a handle that is not a Graphics object:

Error using waitfor
The input object must be a valid MATLAB Graphics object.

I was trying to wait on a user-defined class that is a descendant of the built-in handle class.

#24 Comment By Yair Altman On January 20, 2016 @ 22:57

@Marc – however, you can still use waitfor with Java objects

#25 Comment By Marc On January 21, 2016 @ 00:19

Related question. I’m coding up a simulation, and I’ve got a listener in one object that is dependent on the completion of the listener in another object. (This is not gui work). They are both listening to the same event from the same object. In the dependent class, I tried busy-waiting (with a pause, of course), and it seems that no matter what I do, those two callbacks execute sequentially.

based on this, I presume that matlab is executing all of these callbacks in a single thread, and the dispatcher for the event source is just executing the listeners in order, so that it can’t process the next until the prior one returns?

#26 Comment By Yair Altman On January 21, 2016 @ 00:23

This is not surprising. Matlab’s computational engine is [still] single threaded. I hope and expect this will change in the future. Even when it does, I’m not sure that the listeners would be dispatched asynchronously. I can think of quite a few use-cases where the synchronous listener invocation is actually intended.

#27 Comment By Johan On February 1, 2016 @ 03:41

Hi Yair,

I stumbled onto this page when trying to solve my conundrum. I’m trying to get ‘waitfor/uiwait’ to hold for a message box in a callback. I made a minimum working example like this:

function foo()
uicontrol('style','push','string','push','callback',@cbf,'parent',figure);

function cbf(~,~)
h = msgbox('press ok to continue');
waitfor(h)

But no matter what I do, the waitfor is not respected, that is the pushbutton is not blocked so one can open as many msgboxes as one likes. Very odd behaviour I think, have you by any chance encountered issues like this before?

#28 Comment By Yair Altman On February 1, 2016 @ 12:45

The code that is launched by the button callback runs on a separate thread so waitfor simply blocks execution of that thread, and other callbacks can still process. This is actually documented in waitfor‘s documentation. I suggest to modify the callback code by disabling the button to prevent additional button clicks while one callback is blocked:

function cbf(hButton,~)
  set(hButton,'Enable','off');
  waitfor(msgbox(...))
  set(hButton,'Enable','on');
end

#29 Pingback By Episode 001 – Handling Matlab interrupts in Java – v1ntage.io On July 1, 2017 @ 06:52

[…] that is currently blocked forever inside the Java method. This problem has come up again, and again, and again over the […]

#30 Comment By Brian On July 16, 2017 @ 07:10

Hey I know this is a rather old post, but I wanted to post my solution just in case anyone from the future has the same question. It turns out you can call back into Matlab via JMI to poll the keyboard event queue and trigger an exception if a “Ctrl-C” is waiting. I wrote this up in more detail on my blog at [17]. Let me know what you think.

#31 Comment By Yair Altman On March 30, 2018 @ 12:15

I discussed Ctrl-C interrupts here: [18]

#32 Comment By Ben A. On September 29, 2017 @ 19:55

Hey Yair,
These solutions have proven to be invaluable for me, but sometimes don’t work well for complicated asynchronous situations. I have found an additional approach that has worked very well for me so far.
Python (which we can call natively in MATLAB) has a threading module with an Event object that works easily and reliably. Creating the Event object is just a matter of calling:

myevent = py.threading.Event();

And then making the object available to all interested parties (through appdata, parameter passing, etc.).
The object’s set(), is_set(), clear(), and wait() functions work quickly and reliably in MATLAB, and the wait() function takes a timeout parameter and returns a Boolean value that is true unless the timeout was reached.

#33 Comment By Yair Altman On March 30, 2018 @ 12:19

Unfortunately, using the Python object requires a separate installation of Python. While it is true that many users already have Python installed, many others do not and for such users the Python solution will error. In contrast, the solution that I presented above is based on the built-in waitfor function, and therefore works for all users.


Article printed from Undocumented Matlab: https://undocumentedmatlab.com

URL to article: https://undocumentedmatlab.com/articles/waiting-for-asynchronous-events

URLs in this post:

[1] discussed: http://undocumentedmatlab.com/blog/disable-entire-figure-window/

[2] here: http://undocumentedmatlab.com/blog/matrix-processing-performance/

[3] here: http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/

[4] here: http://undocumentedmatlab.com/blog/cellfun-undocumented-performance-boost/

[5] here: http://undocumentedmatlab.com/blog/performance-scatter-vs-line/

[6] Matlab Performance Tuning: http://undocumentedmatlab.com/courses/Matlab_Performance_Tuning_Course.pdf

[7] Advanced Matlab GUI: http://undocumentedmatlab.com/courses/Advanced_Matlab_GUI_Course_1d.pdf

[8] Matlab-Java programming: http://undocumentedmatlab.com/courses/Using_Java_in_Matlab_Course.pdf

[9] email me: mailto:%20altmany%20@gmail.com?subject=Matlab%20courses&body=Hi%20Yair,%20&cc=;&bcc=

[10] Blocked wait with timeout for asynchronous events : https://undocumentedmatlab.com/articles/blocked-wait-with-timeout-for-asynchronous-events

[11] Matlab callbacks for Java events : https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events

[12] Matlab callbacks for Java events in R2014a : https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a

[13] UDD Events and Listeners : https://undocumentedmatlab.com/articles/udd-events-and-listeners

[14] Undocumented HG2 graphics events : https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events

[15] Matlab callbacks for uifigure JavaScript events : https://undocumentedmatlab.com/articles/matlab-callbacks-for-uifigure-javascript-events

[16] : http://www.mathworks.com/help/matlab/ref/waitfor.html

[17] : https://v1ntage.io/2017/07/01/episode-001-handling-matlab-interrupts-in-java/

[18] : https://undocumentedmatlab.com/blog/mex-ctrl-c-interrupt

Copyright © Yair Altman - Undocumented Matlab. All rights reserved.