问题描述
在clojure中,我可以这样做:
In clojure I can do something like this:
(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
?
推荐答案
在Linux上,您可以分叉一个进程,然后再收集它,如帮助页面?parallel :: mccollect()
;这是一个黑客,而不是像未来一样的强大功能。
On Linux you can fork a process and then collect it later, as illustrated on the help page ?parallel::mccollect()
; this is more of a hack than a robust feature like 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]
设置单个节点工作。
One can implement a similar strategy with snow::sendCall()
/ snow::recvResult()
; see the implementation of snow::clusterCall()
and note that a cluster can be subset, e.g., cl[1]
to set a single node to work. (identically named functions are available in the parallel package, but not exported).
要检查作业是否已完成,请使用 wait = FALSE
。示例:
To check whether a job has finished, use wait = FALSE
. Example:
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个作业都没有完成,则 res
为NULL。
If none of these 3 jobs has been finished, then res
is NULL.
这篇关于计算在一个新的线程,并参考结果以后在R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!