File: parallel.ml

package info (click to toggle)
ocaml 5.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 44,384 kB
  • sloc: ml: 370,196; ansic: 52,820; sh: 27,419; asm: 5,462; makefile: 3,684; python: 974; awk: 278; javascript: 273; perl: 59; fortran: 21; cs: 9
file content (45 lines) | stat: -rw-r--r-- 1,311 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
(* TEST
 include unix;
 hasunix;
 {
   bytecode;
 }{
   native;
 }
*)

let () = Random.init 42

let domain_count = 10

let delays =
  (* These Random calls are intentionally:
   - taken from an independent Random state, not the global state we are testing
   - initialized with make_self_init, to return different delays on each tst run
  *)
  let delay_rng = Random.State.make_self_init () in
  List.init domain_count (fun _i -> Random.State.float delay_rng 0.5)

(* Each domain will start by waiting a random amount, to ensure that
   the Random.int functions we are testing execute in
   non-deterministic order. The Random.int result should remain
   deterministic, as domains are spawned in a deterministic order and
   each domain state is obtaind by splitting the global Random state
   that was initialized with a fixed seed. *)
let f delay () =
  Unix.sleepf delay;
  let a = Random.int 100 in
  let b = Random.int 100 in
  let c = Random.int 100 in
  (a, b, c)

let () =
  delays
  |> List.map (fun delay -> Domain.spawn (f delay))
  |> List.map Domain.join
  |> List.iter (fun (a, b, c) -> Printf.printf "%d %d %d\n%!" a b c)

let () =
  print_endline
    "Note: we observe in this output that the random numbers of each child domain\n\
     appear uncorrelated, yet are produced deterministically."