在foreach

时间:2016-11-24 15:31:23

标签: r foreach parallel-processing

我有一个我想要并行执行的流程,但由于某些strange error而导致我失败。现在我正在考虑组合,并计算主CPU上的失败任务。但是我不知道如何为.combine编写这样的函数。

应该怎么写?

我知道如何编写它们,例如this回答提供了一个示例,但它没有提供如何处理失败的任务,也没有在主服务器上重复任务。

我会做类似的事情:

foreach(i=1:100, .combine = function(x, y){tryCatch(?)} %dopar% {
    long_process_which_fails_randomly(i)
}

但是,如何在.combine函数中使用该任务的输入(如果可以的话)?或者我应该在%dopar%内提供返回标志或列表来计算它?

1 个答案:

答案 0 :(得分:2)

要在combine函数中执行任务,您需要在foreach循环体返回的结果对象中包含额外信息。在这种情况下,这将是一个错误标志和值i。有很多方法可以做到这一点,但这是一个例子:

comb <- function(results, x) {
  i <- x$i
  result <- x$result
  if (x$error) {
    cat(sprintf('master computing failed task %d\n', i))
    # Could call function repeatedly until it succeeds,
    # but that could hang the master
    result <- try(fails_randomly(i))
  }
  results[i] <- list(result)  # guard against a NULL result
  results
}

r <- foreach(i=1:100, .combine='comb',
             .init=vector('list', 100)) %dopar% {
  tryCatch({
    list(error=FALSE, i=i, result=fails_randomly(i))
  },
  error=function(e) {
    list(error=TRUE, i=i, result=e)
  })
}

我很想通过重复执行并行循环来解决这个问题,直到计算完所有任务:

x <- rnorm(100)
results <- lapply(x, function(i) simpleError(''))

# Might want to put a limit on the number of retries
repeat {
  ix <- which(sapply(results, function(x) inherits(x, 'error')))
  if (length(ix) == 0)
    break

  cat(sprintf('computing tasks %s\n', paste(ix, collapse=',')))
  r <- foreach(i=x[ix], .errorhandling='pass') %dopar% {
    fails_randomly(i)
  }

  results[ix] <- r
}

请注意,此解决方案使用.errorhandling选项,如果发生错误,该选项非常有用。有关此选项的更多信息,请参见foreach手册页。