File: create_join.ml

package info (click to toggle)
ocamlnet 4.1.9-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 54,024 kB
  • sloc: ml: 151,939; ansic: 11,071; sh: 2,003; makefile: 1,310
file content (71 lines) | stat: -rw-r--r-- 1,970 bytes parent folder | download | duplicates (7)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
(* Example: Create a number of processes and join them *)

open Printf

let square k =
  (* a process body squaring an int *)
  let r = k * k in
  printf "process: square(%d)=%d\n%!" k r;
  r

let fork_square, join_square = Netmcore_process.def_process square



let compute _ =
  (* a process body that is kind of a main program for our computation *)

  (* start a few processes... *)
  let processes =
    List.map
      (fun k ->
	 let `Process pid = Netmcore_process.start fork_square k in
	 printf "start(%d): pid=%d\n%!" k pid;
	 `Process pid
      )
      [ 1; 2; 3; 4; 5; 6; 7; 8; 9; 10 ] in

  (* and join them, adding up the results *)
  let r =
    List.fold_left
      (fun acc pid ->
	 match Netmcore_process.join join_square pid with
	   | None ->
	       failwith "no result from process"
	   | Some sq ->
	       acc + sq
      )
      0
      processes in

  r

let fork_compute, join_compute = Netmcore_process.def_process compute



let () =
  (* Netmcore.Debug.enable := true; *)
  (* Netplex_controller.Debug.enable := true; *)
  (* Netlog.Debug.enable_module "Netplex_controller"; *)
  (* Netplex_container.Debug.enable := true; *)
  let r =
    Netmcore.run
      ~socket_directory:"run_create_join"
      ~first_process:(fun () -> Netmcore_process.start fork_compute ())
      ~extract_result:(fun ctrl pid ->
                       (* NB. We cannot use {!Netmcore_process.join} here,
                          because we are running in the master process. However,
                          we know that the first process is already finished,
                          and so [join_nowait] is sufficient.
                        *)
                       match Netmcore_process.join_nowait join_compute pid with
                         | None ->
                              failwith "no result"
                         | Some r ->
                              r
                      )
      () in
  printf "Final result: %d\n%!" r;
  ()