perf: add Fut.raise_if_failed, use it in Fiber.check_if_cancelled

This commit is contained in:
Simon Cruanes 2024-03-04 22:05:47 -05:00
parent 86c6edffca
commit 867444d975
No known key found for this signature in database
GPG key ID: EBFFF6F283F3A2B4
4 changed files with 21 additions and 8 deletions

View file

@ -29,6 +29,11 @@ let[@inline] peek self : _ option =
| Done x -> Some x | Done x -> Some x
| Waiting _ -> None | Waiting _ -> None
let[@inline] raise_if_failed self : unit =
match A.get self.st with
| Done (Error ebt) -> Exn_bt.raise ebt
| _ -> ()
let[@inline] is_done self : bool = let[@inline] is_done self : bool =
match A.get self.st with match A.get self.st with
| Done _ -> true | Done _ -> true

View file

@ -91,6 +91,10 @@ val is_failed : _ t -> bool
(** Checks if the future is resolved with [Error _] as a result. (** Checks if the future is resolved with [Error _] as a result.
@since NEXT_RELEASE *) @since NEXT_RELEASE *)
val raise_if_failed : _ t -> unit
(** [raise_if_failed fut] raises [e] if [fut] failed with [e].
@since NEXT_RELEASE *)
(** {2 Combinators} *) (** {2 Combinators} *)
val spawn : on:Runner.t -> (unit -> 'a) -> 'a t val spawn : on:Runner.t -> (unit -> 'a) -> 'a t

View file

@ -291,15 +291,18 @@ let with_on_self_cancel cb (k : unit -> 'a) : 'a =
module Suspend_ = Moonpool.Private.Suspend_ module Suspend_ = Moonpool.Private.Suspend_
let[@inline] check_if_cancelled_ (self : _ t) = Fut.raise_if_failed self.res
let check_if_cancelled () = let check_if_cancelled () =
match Task_local_storage.get k_current_fiber with match Task_local_storage.get k_current_fiber with
| None -> | None ->
failwith "Fiber.check_if_cancelled: must be run from inside a fiber." failwith "Fiber.check_if_cancelled: must be run from inside a fiber."
| Some (Any self) -> | Some (Any self) -> check_if_cancelled_ self
(match peek self with
| Some (Error ebt) -> Exn_bt.raise ebt
| _ -> ())
let[@inline] yield () : unit = let yield () : unit =
check_if_cancelled (); match Task_local_storage.get k_current_fiber with
Suspend_.yield () | None -> failwith "Fiber.yield: must be run from inside a fiber."
| Some (Any self) ->
check_if_cancelled_ self;
Suspend_.yield ();
check_if_cancelled_ self

View file

@ -81,7 +81,8 @@ val wait_block : 'a t -> 'a Fut.or_error
val check_if_cancelled : unit -> unit val check_if_cancelled : unit -> unit
(** Check if the current fiber is cancelled, in which case this raises. (** Check if the current fiber is cancelled, in which case this raises.
Must be run from inside a fiber. Must be run from inside a fiber.
@raise Failure if not. *) @raise e if the current fiber is cancelled with exception [e]
@raise Failure if not run from a fiber. *)
val yield : unit -> unit val yield : unit -> unit
(** Yield control to the scheduler from the current fiber. (** Yield control to the scheduler from the current fiber.