reduce size of critical section

better to reverse the list without holding the lock,
as it allocates and might have to yield to another thread
or domain, pause, etc.
This commit is contained in:
Simon Cruanes 2025-09-08 08:08:29 -04:00
parent 76efa381c3
commit 026465f770
No known key found for this signature in database
GPG key ID: EBFFF6F283F3A2B4

View file

@ -50,18 +50,22 @@ let ready_to_pop ~force ~now self =
self.size > 0 && (force || is_full_ self || timeout_expired_ ~now self) self.size > 0 && (force || is_full_ self || timeout_expired_ ~now self)
let pop_if_ready ?(force = false) ~now (self : _ t) : _ list option = let pop_if_ready ?(force = false) ~now (self : _ t) : _ list option =
protect self.mutex @@ fun () -> let rev_batch_opt =
if ready_to_pop ~force ~now self then ( protect_mutex self.mutex @@ fun () ->
assert (self.q <> []); if ready_to_pop ~force ~now self then (
let batch = assert (self.q <> []);
(* Reverse the list to retrieve the FIFO order. *) let batch = self.q in
List.rev self.q self.q <- [];
in self.size <- 0;
self.q <- []; Some batch
self.size <- 0; ) else
Some batch None
) else in
None match rev_batch_opt with
| None -> None
| Some batch ->
(* Reverse the list to retrieve the FIFO order. *)
Some (List.rev batch)
(* Helper so we can count new elements and prepend them onto the existing [q] in (* Helper so we can count new elements and prepend them onto the existing [q] in
one pass. *) one pass. *)