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 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, 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.
Related posts:
- Matlab callbacks for Java events Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...
- UDD Events and Listeners UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...
- Detecting window focus events Matlab does not have any documented method to detect window focus events (gain/loss). This article describes an undocumented way to detect such events....
- setPrompt – Setting the Matlab Desktop prompt The Matlab Desktop's Command-Window prompt can easily be modified using some undocumented features...
- Matlab and the Event Dispatch Thread (EDT) The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....
- Pause for the better Java's thread sleep() function is much more accurate than Matlab's pause() function. ...


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?
@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.
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:
@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.
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?
@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.
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:
@Tomás – thanks for the information and the workaround
Pingback: Pause for the better | Undocumented Matlab
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
Pingback: Take a break, have a pause() | matlabideas
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!