mirror of
https://github.com/c-cube/ocaml-containers.git
synced 2025-12-06 11:15:31 -05:00
add CCLock.set and tests
This commit is contained in:
parent
4946f367ea
commit
7fec8ca8c2
2 changed files with 30 additions and 0 deletions
|
|
@ -98,13 +98,39 @@ let mutex l = l.mutex
|
|||
let update l f =
|
||||
with_lock l (fun x -> l.content <- f x)
|
||||
|
||||
(*$T
|
||||
let l = create 5 in update l (fun x->x+1); get l = 6
|
||||
*)
|
||||
|
||||
let get l =
|
||||
Mutex.lock l.mutex;
|
||||
let x = l.content in
|
||||
Mutex.unlock l.mutex;
|
||||
x
|
||||
|
||||
let set l x =
|
||||
Mutex.lock l.mutex;
|
||||
l.content <- x;
|
||||
Mutex.unlock l.mutex
|
||||
|
||||
(*$T
|
||||
let l = create 0 in set l 4; get l = 4
|
||||
let l = create 0 in set l 4; set l 5; get l = 5
|
||||
*)
|
||||
|
||||
let incr l = update l (fun x -> x+1)
|
||||
|
||||
let decr l = update l (fun x -> x-1)
|
||||
|
||||
|
||||
(*$R
|
||||
let l = create 0 in
|
||||
let a = Array.init 100 (fun _ -> Thread.create (fun _ -> incr l) ()) in
|
||||
Array.iter Thread.join a;
|
||||
assert_equal ~printer:CCInt.to_string 100 (get l)
|
||||
*)
|
||||
|
||||
(*$T
|
||||
let l = create 0 in incr l ; get l = 1
|
||||
let l = create 0 in decr l ; get l = ~-1
|
||||
*)
|
||||
|
|
|
|||
|
|
@ -67,6 +67,10 @@ val mutex : _ t -> Mutex.t
|
|||
val get : 'a t -> 'a
|
||||
(** Get the value in the lock. The value that is returned isn't protected! *)
|
||||
|
||||
val set : 'a t -> 'a -> unit
|
||||
(** Atomically set the value
|
||||
@since NEXT_RELEASE *)
|
||||
|
||||
val incr : int t -> unit
|
||||
(** Atomically increment the value
|
||||
@since NEXT_RELEASE *)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue