在 OCaml 中异步调用函数

Function getting called asynchronously in OCaml

我正在修改 facebook/pfff 工具,特别是 this file

我在 graph_code_java.ml 中附加细节(节点和边),当遇到节点和顶点时到两个单独的文件:Edges.json 和 GraphSON.json。

最后,在执行所有操作后,我调用了函数 cleanup_graphson,它合并了 Edges.json 和 GraphSON.json。

这是 graph_code_java 我修改后的样子:

let build ?(verbose=true) ?(only_defs=false) root files =
  let g = G.create () in
  G.create_initial_hierarchy g;

  let lookup_fails = Common2.hash_with_default (fun () -> 0) in

(* step1: creating the nodes and 'Has' edges, the defs *)
...
(* step3: creating the 'Use' edges that can rely on recursive inheritance   *)
if verbose then pr2 "\nstep3: extract uses";
files +> Console.progress ~show:verbose (fun k ->
List.iter (fun file ->
 k();
 let readable = Common.readable ~root file in
 let ast = parse ~show_parse_error:false file in
 extract_defs_uses ~phase:Uses ~g ~ast ~readable ~lookup_fails;
));
end;
(* step 4: Merge Edges.json and GraphSON.json *)
if !write_to_graphson = true then
  begin
    pr "cleaning up";
    GS.cleanup_graphson;
  end;
g

函数 cleanup_graphson 看起来像:

let cleanup_graphson =
  pr "Cleaning up!";
  Common.append_file "GraphSON.json" "] \n";
  Common.append_file "Edges.json" "] \n";
  let str = Common.read_file "Edges.json" in
  Common.append_file "GraphSON.json" str

但是当我 运行 程序时,cleanup_graphson 在 其他一切之前被调用 (第 1 步、第 2 步、第 3 步)。除此以外,所有其他步骤都是 运行ning 顺序。我不确定为什么会这样,是因为正在执行文件操作吗?还有其他人遇到过这个问题吗?

P.S: Console.progress 的代码是 here.

感谢您查看我的问题!

除非您专门使用多线程,否则基本上不可能有任何代码被异步执行。

在对这段代码一无所知的情况下,我怀疑是缓冲问题。也许计算按照您期望的顺序进行,但是 pr 的输出在其他输出之前出现。当程序使用两种截然不同的方式写入输出时,这很容易发生。

cleanup_graphson 是一个变量,而不是一个函数。当我修改到下面时,它是顺序执行的。我添加了一个 () 作为 cleanup_graphson.

的参数
let cleanup_graphson ()=
  pr "Cleaning up!";
  Common.append_file "GraphSON.json" "] \n";
  Common.append_file "Edges.json" "] \n";
  let str = Common.read_file "Edges.json" in
  Common.append_file "GraphSON.json" str