From 026465f770e473e34bdd1f2c4e493109a46cc318 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Mon, 8 Sep 2025 08:08:29 -0400 Subject: [PATCH] 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. --- src/client/batch.ml | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/client/batch.ml b/src/client/batch.ml index 88895354..3b8d9e42 100644 --- a/src/client/batch.ml +++ b/src/client/batch.ml @@ -50,18 +50,22 @@ let ready_to_pop ~force ~now self = self.size > 0 && (force || is_full_ self || timeout_expired_ ~now self) let pop_if_ready ?(force = false) ~now (self : _ t) : _ list option = - protect self.mutex @@ fun () -> - if ready_to_pop ~force ~now self then ( - assert (self.q <> []); - let batch = - (* Reverse the list to retrieve the FIFO order. *) - List.rev self.q - in - self.q <- []; - self.size <- 0; - Some batch - ) else - None + let rev_batch_opt = + protect_mutex self.mutex @@ fun () -> + if ready_to_pop ~force ~now self then ( + assert (self.q <> []); + let batch = self.q in + self.q <- []; + self.size <- 0; + Some batch + ) else + None + in + 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 one pass. *)