add CCLock.set and tests

This commit is contained in:
Simon Cruanes 2015-08-31 21:17:48 +02:00
parent 4946f367ea
commit 7fec8ca8c2
2 changed files with 30 additions and 0 deletions

View file

@ -98,13 +98,39 @@ let mutex l = l.mutex
let update l f = let update l f =
with_lock l (fun x -> l.content <- f x) 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 = let get l =
Mutex.lock l.mutex; Mutex.lock l.mutex;
let x = l.content in let x = l.content in
Mutex.unlock l.mutex; Mutex.unlock l.mutex;
x 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 incr l = update l (fun x -> x+1)
let decr 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
*)

View file

@ -67,6 +67,10 @@ val mutex : _ t -> Mutex.t
val get : 'a t -> 'a val get : 'a t -> 'a
(** Get the value in the lock. The value that is returned isn't protected! *) (** 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 val incr : int t -> unit
(** Atomically increment the value (** Atomically increment the value
@since NEXT_RELEASE *) @since NEXT_RELEASE *)