Skip to content

Commit

Permalink
Add Time.with_timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
talex5 committed Nov 12, 2021
1 parent e54466d commit 3bf10e8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib_eio/eio.ml
Expand Up @@ -171,6 +171,8 @@ module Domain_manager = struct
end

module Time = struct
exception Timeout

class virtual clock = object
method virtual now : float
method virtual sleep_until : float -> unit
Expand All @@ -181,6 +183,14 @@ module Time = struct
let sleep_until (t : #clock) time = t#sleep_until time

let sleep t d = sleep_until t (now t +. d)

let with_timeout t d fn =
Fibre.first fn
(fun () -> sleep t d; Error `Timeout)

let with_timeout_exn t d fn =
Fibre.first fn
(fun () -> sleep t d; raise Timeout)
end

module Dir = struct
Expand Down
9 changes: 9 additions & 0 deletions lib_eio/eio.mli
Expand Up @@ -460,6 +460,15 @@ module Time : sig

val sleep : #clock -> float -> unit
(** [sleep t d] waits for [d] seconds. *)

val with_timeout : #clock -> float -> (unit -> ('a, 'e) result) -> ('a, [> `Timeout] as 'e) result
(** [with_timeout clock d fn] runs [fn ()] but cancels it after [d] seconds. *)

exception Timeout

val with_timeout_exn : #clock -> float -> (unit -> 'a) -> 'a
(** [with_timeout_exn clock d fn] runs [fn ()] but cancels it after [d] seconds,
raising exception [Timeout]. *)
end

module Dir : sig
Expand Down

0 comments on commit 3bf10e8

Please sign in to comment.