Threaded Command Object

Forces

GUI code needs to responsive to input while work is being done. We want to encapsulate the information needed to perform a job. We're in C++ Windows/Mac where certain issue constrain what gui threads and non-gui threads can do.

Therefore:

Use threaded command object (which is WHAT, exactly?) to do the work. See also Command Pattern, Command Object.

To keep application thread-safe, avoid calling functions in the model while the threaded command object is running.

An issue in Microsoft Windows is that a GUI thread cannot safely call mutex, semaphores, etc. that could force the thread to wait, unless you use Msg Wait For Multiple Objects, which includes the thread's window message queue as one of the objects to wait on, otherwise there could be deadlock if the GUI thread has to wait on a mutex while the operating system tries to send an event to its window.

Mac Os 9 preemptive threads cannot call GUI functions at all (they used to not be able to do much at all except image processing - that changed several years ago). They can make network calls, and maybe file system and other non-GUI calls. On MacOS 9, it is safe for the main (GUI) thread to wait on a semaphore, because the OS integrated theGUI-event-polling mechanism with the semaphore system.

before threaded command objects are created, gui calls model objects safely, without needing synchronization

when user initiates an action, gui creates threaded command object

while threaded command object is running, that 'action' part of the gui is disabled, (or maybe entire gui is disabled except for the cancel button - depending on how fine-grained your command objects and synchronization are).

while threaded command object is running, gui does not make calls to the parts of the model associated with that command object

command object makes calls to model as necessary to do its work

command object notifies gui of completion / progress using window-events on Microsoft windows. On MacOS, main thread polls a thread-safe message queue

immediately after signalling the main gui thread, command-thread deletes the command object

gui can now query model safely again, and zeroes out the pointer to the dead command-object.

In java, use What Its Name method to asynchronously update gui from a non-main thread...


Swing Utilities.invokeLater()?


Mac Osx GUIs (Carbon and Cocoa) are also not thread-safe: only the main thread should do anything in the GUI.

See original on c2.com