如何在OCaml中使用多核进行蒙特卡罗模拟?

9

OCaml进程只能使用一个核心,为了使用多个核心,我必须运行多个进程。

是否有任何OCaml框架可用于并行化蒙特卡罗模拟?

2个回答

8
使用以下invoke组合子将函数应用于另一个(分叉的)进程中的值,然后在应用()值时阻塞等待其结果:
  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

3

2
ocaml4multicore 可用(有限制),请参见:http://www.algo-prog.info/ocmc/web/ - nlucaroni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接