22 stick with the non-atomic references in `gensym`. Use capsules to ensure that
33 gensym is safe for parallel access (and the code will compile). *)
44
5- open Basement
5+ open Await
66
77(* Here is an example snippet to show how to create and use capsules. *)
88let safe_ref (init : int ) =
9- (* Create capsule and extract key to bind the type variable *)
10- let (P key ) = Capsule. create () in
9+ (* Create a capsule guarded by a mutex and extract the latter *)
10+ let (P mutex ) = Capsule.Mutex . create () in
1111 (* Create encapsulated data bound to the same key type *)
1212 let r = Capsule.Data. create (fun () -> ref init) in
13- (* Create mutex from key *)
14- let mutex = Capsule.Mutex. create key in
1513
1614 (* Access with lock *)
17- let read () =
18- Capsule.Mutex. with_lock mutex ~f: (fun password ->
19- Capsule.Data. extract r ~password ~f: ( fun ( r : int ref ) -> ! r) )
15+ let read (w : Await.t ) =
16+ Capsule.Mutex. with_lock w mutex ~f: (fun access ->
17+ let r = Capsule.Data. unwrap r ~access in ! r )
2018 in
21- let write (v : int ) =
22- Capsule.Mutex. with_lock mutex ~f: (fun password ->
23- Capsule.Data. extract r ~password ~f: ( fun r -> r := v) )
19+ let write (w : Await.t ) v =
20+ Capsule.Mutex. with_lock w mutex ~f: (fun access ->
21+ let r = Capsule.Data. unwrap r ~access in r := v)
2422 in
2523 (read, write)
2624
@@ -33,21 +31,22 @@ let gensym =
3331let parallel_read_write par =
3432 let r = safe_ref 0 in
3533 let read, write = r in
36- Parallel. fork_join2 par
37- (fun _ ->
38- for _ = 1 to 1000 do
39- ignore (read () )
40- done )
41- (fun _ ->
42- for i = 1 to 1000 do
43- write i
44- done )
45- |> ignore
34+ let #(() , () ) =
35+ Parallel. fork_join2 par
36+ (fun _ -> Await_blocking. with_await Terminator. never ~f: (fun w ->
37+ for _ = 1 to 1000 do
38+ ignore (read w)
39+ done ))
40+ (fun _ -> Await_blocking. with_await Terminator. never ~f: (fun w ->
41+ for i = 1 to 1000 do
42+ write w i
43+ done ))
44+ in ()
4645
4746(* Test that gensym produces distinct symbols in parallel *)
4847
4948let gensym_pair par =
50- let s1, s2 =
49+ let #( s1, s2) =
5150 Parallel. fork_join2 par (fun _ -> gensym () ) (fun _ -> gensym () )
5251 in
5352 assert (s1 <> s2)
@@ -56,8 +55,7 @@ let gensym_pair par =
5655let run_parallel ~f =
5756 let module Scheduler = Parallel_scheduler_work_stealing in
5857 let scheduler = Scheduler. create () in
59- let monitor = Parallel.Monitor. create_root () in
60- let result = Scheduler. schedule scheduler ~monitor ~f in
58+ let result = Scheduler. parallel scheduler ~f in
6159 Scheduler. stop scheduler;
6260 result
6361
0 commit comments