Abro: synchronization and cancellation examples
In the Introduction, I wrote about a common pattern in web programming: the synchronization of asynchronous events reception. You write a program that must trigger an action after two different events occurs.
ABO: when A and B, then O
Lets name the two events we are waiting for A and B, and the action to trigger is emitting an event O (as for output). The real action can be triggered in the event handler of O.
In pure JavaScript, writing such handling code requires to manage a state to know if whether B has occurred in the callback of A (and reciprocally), and to decide if O must be triggered.
In HipHop, we write as follows:
(seq& (par& (await& (now& A)) (await& (now& B))) (emit& O))
The code is very clear for those familiar with Hop's prefix syntax. In sequence, we begin by waiting for A and B concurrently. When both has occurred, and immediately after the occurrence of the last event, par& terminates and the emit& expression is executed. par& termination is a synchronization barrier.
We can define a Hop function for constructing ABO programs by just enclosing the above program in a define expression:
(define (abo& A B O) (seq& (par& (await& (now& A)) (await& (now& B))) (emit& O)))
ABRO: ABO+Cancellation
Lets say that now we want to cancel the whole program when a specific event R (for reset) occur. For instance, the R event might be triggered when the user clicks a Cancel button, or when a timeout expires.
Here is how we write ABRO in HipHop, inside Hop, using the above abo& function:
(define (abro& A B R O) (abort& (now& R) (abo& A B O)))
We simply enclose the ABO program in an abort& expression.
An abort& expression contains a condition (an host-expression) and a body (at least one hiphop-expression). The semantics of abort& are as follows:
- At the first reaction, the body expressions are executed as if they were enclosed in a seq& expression.
- At subsequent reactions, the host-expression is first evaluated. If true, then the whole abort& expression terminates instantaneously, killing the body. If false, the body resumes normally its execution.
ABCO: ABO+C (and +D, +E, etc.)
Lets go back to the ABO example, and now, we want to change the program to wait also for a third event C before triggering the O action.
We simply extend the par& expression to add an additional await& expression for the event C. The ABCO programs could be written as follows:
(seq& (par& (await& (now& A)) (await& (now& B)) (await& (now& C))) (emit& O))
Return to Top
Page last modified Sat May 25 09:56:47 2013.