在新线程中计算并稍后在 R 中引用结果

Compute in a new thread and refer to results later in R

在 clojure 中我可以这样做:

(def x 
  ;; perform some expensive computation in a new thread
  ;; the repl is not blocked, so you can go on do something else
  (future 
    (do 
      (Thread/sleep 500) 
      3.14)))
;; ... do something else
;; now when you need x
;; just deref the future, get 3.14
@x    

R 中有类似的东西吗?

在 Linux 上,您可以 fork 一个进程,然后在稍后收集它,如帮助页面 ?parallel::mccollect() 所示;这更像是一种 hack,而不是像 future 这样的强大功能。

> p <- mcparallel({ Sys.sleep(5); "done" })
> sqrt(1:5)
[1] 1.000000 1.414214 1.732051 2.000000 2.236068
> mccollect(p)
$`15666`
[1] "done"

可以使用 snow::sendCall() / snow::recvResult() 实施类似的策略;查看 snow::clusterCall() 的实现并注意集群可以是子集,例如 cl[1] 以设置单个节点工作。 (同名函数在 parallel 包中可用,但不导出)。

要检查作业是否已完成,请使用 wait = FALSE。示例:

require(parallel)
p1 = mcparallel({Sys.sleep(90); list(tag = "job1", res = 1})
p2 = mcparallel({Sys.sleep(80); 2})
p3 = mcparallel({Sys.sleep(60); 3})
res = mccollect(list(p1, p2, p3), wait = FALSE)
is.null(res)

如果这 3 个作业中的 none 已完成,则 res 为 NULL。