Download The JoCaml language Release 3.12 - The JoCaml system

Transcript
18
# def count(n) & tick() = count(n-1)
# or count(0) & wait() = reply to wait
# ;;
val tick : unit Join.chan = <abstr>
val count : int Join.chan = <abstr>
val wait : unit -> unit = <fun>
By sending an initial message n on count, we enable counting n events.
# let n = 5
# ;;
val n : int = 5
# spawn count(n)
# ;;
- : unit = ()
Finally, one can wait for the n events to occur by calling the synchronous channel wait. The
reaction rule count(0) & wait() = reply to wait is to be noticed: the formal argument of
count is a pattern, here the integer constant 0. This means that the guarded process will be firable
only when message 0 is pending on channel count — See Section ??.
Beware, if at some time, count(0), tick() and wait() are active, then the clause count(n) &
tick() = count(n-1) can be selected. As an imediate consequence, count(0) will never be active
again, and the agent waiting on wait will stay blocked. However, if at most n messages are sent
on tick, then the device above works as expected.
The “count n events” idiom is so frequent that we build a countdown generator as follows:
# let create_countdown n =
#
def count(n) & tick() = count(n-1)
#
or count(0) & wait() = reply to wait in
#
spawn count(n) ;
#
tick,wait
# ;;
val create_countdown : int -> unit Join.chan * (unit -> unit) = <fun>
Now we get a fresh countdown started at n by create_countdown n. More precisely, “a fresh
countdown” is the pair of asynchronous tick and synchronous wait, where wait will answer once n
messages are sent on tick. Also observe that the internal channel count is now kept secret and
that the countdown generator takes care of initialisation.
In the following code, n messages are sent on tick by n asynchronous agents once they have
printed one digit, while the closing parenthesis is printed only after wait() has returned.
# let n = 5
# ;;
val n : int = 5
# let tick,wait = create_countdown n
# ;;
val tick : unit Join.chan = <abstr>
val wait : unit -> unit = <fun>