module Lwt_switch:sig..end
type id
val free : id -> unit Lwt.t
val f : unit -> id Lwt.t
val g : unit -> id Lwt.t
val h : unit -> id Lwt.t
Now you want to calls f, g and h in parallel. You can
simply do:
lwt idf = f () and idg = g () and idh = h () in
...
However, one may wants to handle possible failures of f (), g
() and h (), and disable all allocated resources if one of
these three threads fails. This may be hard since you have to
remember which one failed and which one returned correctly.
Now we change a little bit the interface:
val f : ?switch : Lwt_switch.t -> unit -> id Lwt.t
val g : ?switch : Lwt_switch.t -> unit -> id Lwt.t
val h : ?switch : Lwt_switch.t -> unit -> id Lwt.t
and the code becomes:
let switch = Lwt_switch.create () in
try_lwt
lwt idf = f ~switch () and idg = g ~switch () and idh = h ~switch () in
...
with exn ->
lwt () = Lwt_switch.turn_off switch in
raise_lwt exn
type t
val create : unit -> tcreate () creates a new switch.val is_on : t -> boolis_on switch returns true if the switch is currently on, and
false otherwise.val turn_off : t -> unit Lwt.tturn_off switch turns off the switch. It calls all registered
hooks, waits for all of them to terminates, and the returns. If
one of the hook failed, then it will fail with one of the
exception raised by hooks. If the switch is already off, then it
does nothing.exception Off
val check : t option -> unitcheck switch does nothing if switch is None or contains an
switch that is currently on, and raise Lwt_switch.Off otherwise.val add_hook : t option -> (unit -> unit Lwt.t) -> unitadd_hook switch f registers f so it will be called when
Lwt_switch.turn_off is invoked. It does nothing if switch is
None. If switch contains an switch that is already off then
Lwt_switch.Off is raised.val add_hook_or_exec : t option -> (unit -> unit Lwt.t) -> unit Lwt.tadd_hook_or_exec switch f is the same as Lwt_switch.add_hook except
that if the switch is already off, then f is called
immediatly.