From 590bd4ccc537795050885d437803be563c593ebe Mon Sep 17 00:00:00 2001 From: "Christoph M. Wintersteiger" Date: Thu, 26 Mar 2026 21:44:14 +0000 Subject: [PATCH] Add try_get functions for Rvars --- src/sync/lock.ml | 8 ++++++++ src/sync/lock.mli | 4 ++++ src/thread/rvar.ml | 6 ++++++ src/thread/rvar.mli | 3 +++ 4 files changed, 21 insertions(+) diff --git a/src/sync/lock.ml b/src/sync/lock.ml index 514dcd5cd..d33588e5a 100644 --- a/src/sync/lock.ml +++ b/src/sync/lock.ml @@ -35,6 +35,14 @@ let get l = Mutex.unlock l.mutex; x +let try_get l = + if Mutex.try_lock l.mutex then ( + let x = l.content in + Mutex.unlock l.mutex; + Some x + ) else + None + let set l x = Mutex.lock l.mutex; l.content <- x; diff --git a/src/sync/lock.mli b/src/sync/lock.mli index 377d73ae7..2983e8a76 100644 --- a/src/sync/lock.mli +++ b/src/sync/lock.mli @@ -25,6 +25,10 @@ val get : 'a t -> 'a (** Atomically get the value in the lock. The value that is returned isn't protected! *) +val try_get : 'a t -> 'a option +(** Atomically get the value in the lock, but only if we get the lock + immediately. *) + val set : 'a t -> 'a -> unit (** Atomically set the value. *) diff --git a/src/thread/rvar.ml b/src/thread/rvar.ml index 3f4ca5195..d7d5726db 100644 --- a/src/thread/rvar.ml +++ b/src/thread/rvar.ml @@ -17,6 +17,12 @@ type 'a st = { type 'a t = { st: 'a st Lock.t } [@@unboxed] let[@inline] get (self : 'a t) : 'a = (Lock.get self.st).v + +let[@inline] try_get (self : 'a t) : 'a option = + match Lock.try_get self.st with + | Some v -> Some v.v + | None -> None + let[@inline] pp ppx out self : unit = ppx out (get self) let[@inline] return x = diff --git a/src/thread/rvar.mli b/src/thread/rvar.mli index 46fce8859..847a64023 100644 --- a/src/thread/rvar.mli +++ b/src/thread/rvar.mli @@ -11,6 +11,9 @@ val return : 'a -> 'a t val get : 'a t -> 'a (** Get the current value. *) +val try_get : 'a t -> 'a option +(** Get the current value, but only if we get the lock immediately. *) + val pp : 'a Fmt.printer -> 'a t Fmt.printer exception Frozen