瀏覽代碼

Use a mutex

Rudy Ges 1 月之前
父節點
當前提交
1132888f96
共有 1 個文件被更改,包括 13 次插入13 次删除
  1. 13 13
      src/core/ds/atomicLazy.ml

+ 13 - 13
src/core/ds/atomicLazy.ml

@@ -1,21 +1,21 @@
 open Atomic
 
-type 'a atomic_lazy = {
-  mutable value: 'a option;
-  computed: bool Atomic.t;
-  compute: unit->'a
+type 'a t = {
+	mutable value: 'a option;
+	mutex: Mutex.t;
+	compute: unit->'a
 }
 
 let from_fun f =
-  { value = None; computed = Atomic.make false; compute = (fun () -> f()) }
+	{ value = None; mutex = Mutex.create (); compute = (fun () -> f()) }
 
 let force lazy_val =
-  if not (Atomic.get lazy_val.computed) then begin
-    let result = lazy_val.compute () in
-    lazy_val.value <- Some result;
-    Atomic.set lazy_val.computed true;
-	end;
-  match lazy_val.value with
-  | Some v -> v
-  | None -> failwith "Value not computed"
+	if Option.is_none lazy_val.value then
+		Mutex.protect lazy_val.mutex (fun () ->
+			let result = lazy_val.compute () in
+			lazy_val.value <- Some result;
+		);
+	match lazy_val.value with
+	| Some v -> v
+	| None -> failwith "Value not computed"