読者です 読者をやめる 読者になる 読者になる

osiire’s blog

ふしぎなそふとやさん

0から順番の数字を返す関数をスレッドセーフに

(* to compile, ocamlc  -thread unix.cma threads.cma mts.ml *)
let nums =
  let with_lock m f x =
    Mutex.lock m; 
    let r = f x in
    Mutex.unlock m;
    r
  in
  let c = ref ~-1 in
  let m = Mutex.create () in
  fun () -> 
    with_lock m (fun () -> incr c; !c) ()


let _ = 
  print_int (nums ());
  print_int (nums ());
  print_int (nums ());
  print_int (nums ())