mirror of
https://github.com/c-cube/ocaml-containers.git
synced 2025-12-07 11:45:31 -05:00
threads/CCLock: add try_with_lock to wrap Mutex.try_lock
This commit is contained in:
parent
ef07decbac
commit
35859508c0
2 changed files with 20 additions and 1 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue