捕获R中新线程的输出

时间:2013-10-04 20:42:48

标签: r multithreading parallel-processing output snow

我正在运行一个多线程R脚本,但是我在从集群生成输出时遇到了麻烦。

outFun <- function()
{
  cat(sample(0:9,1));
}
require(snow)
clust <- makeCluster(4)
clusterExport(clust,"outFun")
clustFun <- function(i){outFun()}
clusterApplyLB(clust,1:8,clustFun)

我理解我没有看到outFun()的任何输出,因为它在一个新的R线程中,但是我希望有一些方法可以将这个输出转发回主线程,所以它打印时可见。

编辑:This question为Linux机器解决了这个问题,但该解决方案不适用于Windows。给出的解决方法是简单地使用文件输出,但我很好奇是否有人知道能够将输出实际发送回Windows中的主线程的解决方案。

1 个答案:

答案 0 :(得分:2)

makeCluster outfile=""选项在Windows上不适用于Rgui,因为Rgui不会将子进程的输出发送到显示窗口。但是,outfile=""可以与Rterm程序一起使用,因为它是一个简单的控制台程序:

C:\Program Files\R\R-3.0.2\bin\i386> rterm -q
> library(parallel)
> clust <- makeCluster(4, outfile="")
starting worker pid=1596 on localhost:11862 at 09:13:30.005
starting worker pid=1192 on localhost:11862 at 09:13:30.342
starting worker pid=1616 on localhost:11862 at 09:13:30.679

“起始工作者”消息在执行slaveLoop函数之前来自工作进程。您还应该看到工作人员执行任务的输出:

> clusterEvalQ(clust, message("hello"))
hello
hello
hello
hello
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL