9

OCaml process can use just one core and in order to use multiple cores I have to run several processes.

Are there any OCaml frameworks to use to parallelize Monte Carlo simulations?

Chris
  • 26,361
  • 5
  • 21
  • 42
Alfa07
  • 3,314
  • 3
  • 26
  • 39

2 Answers2

8

Use the following invoke combinator to apply a function to a value in another (forked) process and then block waiting for its result when the () value is applied:

  let invoke (f : 'a -> 'b) x : unit -> 'b =
    let input, output = Unix.pipe() in
    match Unix.fork() with
    | -1 -> (let v = f x in fun () -> v)
    | 0 ->
        Unix.close input;
        let output = Unix.out_channel_of_descr output in
        Marshal.to_channel output (try `Res(f x) with e -> `Exn e) [];
        close_out output;
        exit 0
    | pid ->
        Unix.close output;
        let input = Unix.in_channel_of_descr input in
        fun () ->
          let v = Marshal.from_channel input in
          ignore (Unix.waitpid [] pid);
          close_in input;
          match v with
          | `Res x -> x
          | `Exn e -> raise e
J D
  • 48,105
  • 13
  • 171
  • 274
3

Currently, the only way to do it is with MPI, and you can find OCaml bindings for it on Xavier Leroy's website.

Chris
  • 26,361
  • 5
  • 21
  • 42
nlucaroni
  • 47,556
  • 6
  • 64
  • 86