threads/CCLock: add try_with_lock to wrap Mutex.try_lock

This commit is contained in:
David Sheets 2016-12-16 15:26:23 +00:00
parent ef07decbac
commit 35859508c0
2 changed files with 20 additions and 1 deletions

View file

@ -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

View file

@ -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