Skip to content

Commit 12bf9f5

Browse files
committed
Add bind_on and await_on to Picos_lwt
1 parent 65f36b1 commit 12bf9f5

File tree

4 files changed

+41
-1
lines changed

4 files changed

+41
-1
lines changed

lib/picos_lwt.unix/picos_lwt_unix.ml

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ let rec notify () =
4141
end
4242
else notify ()
4343

44-
module System = struct
44+
module System : Picos_lwt.System = struct
4545
let sleep = Lwt_unix.sleep
4646

4747
type trigger = unit Lwt.t * unit Lwt.u

lib/picos_lwt.unix/picos_lwt_unix.mli

+3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33

44
open Picos
55

6+
val system : (module Picos_lwt.System)
7+
(** The system module for Unix. *)
8+
69
val run_fiber : Fiber.t -> (Fiber.t -> unit) -> unit Lwt.t
710
(** [run_fiber fiber main] runs the [main] program as the specified [fiber] as a
811
promise with {!Lwt} as the scheduler using a {!Lwt_unix} based

lib/picos_lwt/picos_lwt.ml

+31
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,37 @@ let await promise =
3535
| Return value -> value
3636
| Fail exn -> raise exn
3737

38+
let bind_on (module System : System) thunk =
39+
let trigger = System.trigger () in
40+
let promise = Lwt.bind (System.await trigger) thunk in
41+
System.signal trigger;
42+
promise
43+
44+
let await_on (module System : System) promise =
45+
let computation = Computation.create ~mode:`LIFO () in
46+
let trigger = System.trigger () in
47+
let promise =
48+
Lwt.bind (System.await trigger) @@ fun () ->
49+
Lwt.try_bind
50+
(fun () -> promise)
51+
(fun value ->
52+
Computation.return computation value;
53+
Lwt.return_unit)
54+
(fun exn ->
55+
Computation.cancel computation exn empty_bt;
56+
Lwt.return_unit)
57+
in
58+
System.signal trigger;
59+
let trigger = Trigger.create () in
60+
if Computation.try_attach computation trigger then begin
61+
match Trigger.await trigger with
62+
| None -> Computation.peek_exn computation
63+
| Some (exn, bt) ->
64+
Lwt.cancel promise;
65+
Printexc.raise_with_backtrace exn bt
66+
end
67+
else Computation.peek_exn computation
68+
3869
let[@alert "-handler"] rec go : type a r.
3970
Fiber.t ->
4071
(module System) ->

lib/picos_lwt/picos_lwt.mli

+6
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ val await : 'a Lwt.t -> 'a
1717

1818
include module type of Intf
1919

20+
val bind_on : (module System) -> (unit -> 'a Lwt.t) -> 'a Lwt.t
21+
(** *)
22+
23+
val await_on : (module System) -> 'a Lwt.t -> 'a
24+
(** *)
25+
2026
val run_fiber : (module System) -> Fiber.t -> (Fiber.t -> unit) -> unit Lwt.t
2127
(** [run_fiber (module System) fiber main] runs the [main] program as the
2228
specified [fiber] as a promise with {!Lwt} as the scheduler using the given

0 commit comments

Comments
 (0)