From 35859508c0acf02593b161bff00daca8f2127612 Mon Sep 17 00:00:00 2001 From: David Sheets Date: Fri, 16 Dec 2016 15:26:23 +0000 Subject: [PATCH] threads/CCLock: add try_with_lock to wrap Mutex.try_lock --- src/threads/CCLock.ml | 12 ++++++++++++ src/threads/CCLock.mli | 9 ++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/threads/CCLock.ml b/src/threads/CCLock.ml index cd9aa456..c1f0bf14 100644 --- a/src/threads/CCLock.ml +++ b/src/threads/CCLock.ml @@ -35,6 +35,18 @@ let with_lock l f = assert_equal 10 (get l) *) +let try_with_lock l f = + if Mutex.try_lock l.mutex + then + try + let x = f l.content in + Mutex.unlock l.mutex; + Some x + with e -> + Mutex.unlock l.mutex; + raise e + else None + module LockRef = struct type 'a t = 'a lock let get t = t.content diff --git a/src/threads/CCLock.mli b/src/threads/CCLock.mli index 75e4b07c..7569e26e 100644 --- a/src/threads/CCLock.mli +++ b/src/threads/CCLock.mli @@ -18,6 +18,12 @@ val with_lock : 'a t -> ('a -> 'b) -> 'b the lock [l], in a critical section. If [f x] fails, [with_lock l f] fails too but the lock is released *) +val try_with_lock : 'a t -> ('a -> 'b) -> 'b option +(** [try_with_lock l f] runs [f x] in a critical section if [l] is not + locked. [x] is the value protected by the lock [l]. If [f x] + fails, [try_with_lock l f] fails too but the lock is released + @since NEXT_RELEASE *) + (** Type allowing to manipulate the lock as a reference @since 0.13 *) module LockRef : sig @@ -48,7 +54,8 @@ val mutex : _ t -> Mutex.t (** Underlying mutex *) val get : 'a t -> 'a -(** Get the value in the lock. The value that is returned isn't protected! *) +(** Atomically get the value in the lock. The value that is returned + isn't protected! *) val set : 'a t -> 'a -> unit (** Atomically set the value