R中的并行while循环 [英] Parallel while loop in R

查看:167
本文介绍了R中的并行while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以并行化R中的while循环.

I would like to know if / how it is possible to parallelize a while loop in R.

如果不可能或无法合理地认为它很难完成,我将不胜感激,可以使用并行的for循环代替.

If it is not possible or reasonably considered too difficult to accomplish, I would greatly appreciate an alternative, possibly using a parallel for loop instead.

推荐答案

您可以将Future与任何循环的R构造(包括for()while()循环)一起使用.期货在未来包中实现(我是作者).

You can use futures with any looping R construct including for() and while() loops. Futures are implemented in the future package (I'm the author).

不清楚您要为while循环使用什么条件.那将有助于给出更精确的答案.这是一个示例,其中while条件 not 不取决于所计算的任何结果:

It is not clear what condition you want to use for your while loop. That would have helped give a more precise answer. Here is an example where the while condition does not depend on any of the results calculated:

library("listenv")
library("future")
plan(multiprocess, workers = 2L)

res <- listenv()

ii <- 1L
while (ii <= 5) {
  ## This is evaluated in parallel and will only block
  ## if all workers are busy.
  res[[ii]] %<-% {
    list(iteration = ii, pid = Sys.getpid())
  }
  ii <- ii + 1L
}

## Resolve all futures (blocks if not already finished)
res <- as.list(res)

str(res)
List of 5
 $ :List of 2
  ..$ iteration: int 1
  ..$ pid      : int 15606
 $ :List of 2
  ..$ iteration: int 2
  ..$ pid      : int 15608
 $ :List of 2
  ..$ iteration: int 3
  ..$ pid      : int 15609
 $ :List of 2
  ..$ iteration: int 4
  ..$ pid      : int 15610
 $ :List of 2
  ..$ iteration: int 5
  ..$ pid      : int 15611

如果您希望while条件取决于一个或多个并行结果的结果(在res[[ii]]中),那么事情会变得更加复杂,因为这时您需要弄清楚将来会发生什么(=并行任务)仍未解决;您应该在5个迭代后再检查一次还是应该等待.那是并行算法的设计问题,而不是如何实现.一切皆有可能.

If you want your while condition to depend on the outcome of one or more of the parallel results (in res[[ii]]) then things become much more complicated, because then you need to figure out what should happen if the future (= parallel task) is still not resolved; should you check back, say, 5 iterations later, or should you wait. That's a design issue of the parallel algorithm and not how to implement. Anything is possible.

PS.我不明白收到这个问题的不赞成票.可能是因为您的问题措辞不佳/不太清楚-记住要尽可能精确地尝试帮助帮助者帮助您".如果降票是由于while循环,我(显然)会不同意.

PS. I don't understand the downvotes this question received. It could be that it's because your question is poorly phrased / not very clear - remember to try as far as possible to "help the helper help you" by being as precise as possible. If the downvotes are because of the while loop, I (obviously) beg to disagree.

这篇关于R中的并行while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆