Waiting for asynchronous events

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 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
    % Create and start the separate timeout timer thread
    hTimer = timer('TimerFcn',@(h,e)object.setDone(true), 'StartDelay',timeout);
    % Wait for the object property to change or for timeout, whichever comes first
    % 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


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

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
    pause(delay);  % a slight pause to let all the data gather

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, here, here and here).

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, Advanced Matlab GUI and/or Matlab-Java programming seminars in Geneva on August 21-23, 2012 – email me (altmany at gmail dot com) for details.

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

Tags: , , , ,

Bookmark and SharePrint Print

30 Responses to Waiting for asynchronous events

  1. Brad Stiritz says:

    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,

    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?

    • @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.

  2. Alex says:

    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)
    catch ME
    error('Function did not converge in 60 seconds')
    • @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.

  3. Brad Stiritz says:


    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?

    • @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.

  4. Tomás Peyré says:

    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
  5. Pingback: Pause for the better | Undocumented Matlab

  6. Jim Hokanson says:

    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.


  7. Pingback: Take a break, have a pause() | matlabideas

  8. Rafael says:

    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?


  9. Bolivar says:

    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!

  10. Bolivr Djamen says:

    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

  11. Daniel R says:

    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?

    • @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.

  12. Jan says:

    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?


    • Jan says:

      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:


      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

  13. William says:

    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.

  14. Peter says:

    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).

  15. Marc Passy says:

    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.

  16. Marc says:

    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?

    • 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.

  17. Johan says:

    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()
    function cbf(~,~)
    h = msgbox('press ok to continue');

    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?

    • 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,~)
  18. Pingback: Episode 001 – Handling Matlab interrupts in Java – v1ntage.io

  19. Brian says:

    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 https://v1ntage.io/2017/07/01/episode-001-handling-matlab-interrupts-in-java/. Let me know what you think.

Leave a Reply

Your email address will not be published. Required fields are marked *