【发布时间】:2013-04-11 09:16:46
【问题描述】:
我正在使用 R 包 foreach() 和 %dopar% 并行进行长时间(~天)计算。如果其中一个产生错误,我希望能够停止整个计算集。但是,我还没有找到实现这一点的方法,并且从文档和各种论坛中我没有发现任何迹象表明这是可能的。特别是,break() 不起作用,stop() 仅停止当前计算,而不是整个 foreach 循环。
请注意,我不能使用简单的 for 循环,因为最终我想使用 doRNG 包将其并行化。
这是我正在尝试的一个简化的、可重现的版本(此处与%do% 串联显示,但在使用doRNG 和%dopar% 时我遇到了同样的问题)。请注意,实际上我想并行运行此循环的所有元素(此处为 10 个)。
library(foreach)
myfunc <- function() {
x <- foreach(k = 1:10, .combine="cbind", .errorhandling="stop") %do% {
cat("Element ", k, "\n")
Sys.sleep(0.5) # just to show that stop does not cause exit from foreach
if(is.element(k, 2:6)) {
cat("Should stop\n")
stop("Has stopped")
}
k
}
return(x)
}
x <- myfunc()
# stop() halts the processing of k=2:6, but it does not stop the foreach loop itself.
# x is not returned. The execution produces the error message
# Error in { : task 2 failed - "Has stopped"
我想要实现的是整个 foreach 循环可以在某些条件下立即退出(这里,当遇到 stop() 时)。
我发现没有办法通过foreach 实现这一点。看来我需要一种方法来向所有其他进程发送消息以使它们也停止。
如果不能使用foreach,有没有人知道替代方案?我也尝试使用parallel::mclapply 来实现这一点,但这也不起作用。
> sessionInfo()
R version 3.0.0 (2013-04-03)
Platform: x86_64-apple-darwin10.8.0 (64-bit)
locale:
[1] C/UTF-8/C/C/C/C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] foreach_1.4.0
loaded via a namespace (and not attached):
[1] codetools_0.2-8 compiler_3.0.0 iterators_1.0.6
【问题讨论】:
-
不能用
for代替吗? -
不,因为最终我想使用 doRNG 包并行化它。 (抱歉,我在原始帖子中没有说清楚:我已经对其进行了编辑以使其明确。)
-
根据您的其他 cmets,您可能希望每个子进程能够在失败时设置一个“标志”对象,并使该对象可供所有子进程读取。它们都必须有一些内部断点或等效的东西来定期检查“标志”的值,这样它们都可以自行终止。
标签: r foreach parallel-processing break