mirror of
https://github.com/c-cube/ocaml-containers.git
synced 2026-01-28 03:44:51 -05:00
Merge pull request #89 from dsheets/try-lock
threads/CCLock: add `try_with_lock` to wrap `Mutex.try_lock` (thansk @dsheets)
This commit is contained in:
commit
478a1be535
2 changed files with 20 additions and 1 deletions
|
|
@ -35,6 +35,18 @@ let with_lock l f =
|
||||||
assert_equal 10 (get l)
|
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
|
module LockRef = struct
|
||||||
type 'a t = 'a lock
|
type 'a t = 'a lock
|
||||||
let get t = t.content
|
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]
|
the lock [l], in a critical section. If [f x] fails, [with_lock l f]
|
||||||
fails too but the lock is released *)
|
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
|
(** Type allowing to manipulate the lock as a reference
|
||||||
@since 0.13 *)
|
@since 0.13 *)
|
||||||
module LockRef : sig
|
module LockRef : sig
|
||||||
|
|
@ -48,7 +54,8 @@ val mutex : _ t -> Mutex.t
|
||||||
(** Underlying mutex *)
|
(** Underlying mutex *)
|
||||||
|
|
||||||
val get : 'a t -> 'a
|
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
|
val set : 'a t -> 'a -> unit
|
||||||
(** Atomically set the value
|
(** Atomically set the value
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue