Lwt switches
Switch has two goals:
For example, consider the following interface:
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 call f
, g
and h
in parallel. You can
simply do:
lwt idf = f () and idg = g () and idh = h () in
...
However, one may want 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 if we change the interface a little bit:
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
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 of switches.
Exception raised when trying to add a hook to a switch that is already off.