简体   繁体   English

具有递归功能的并行计算

[英]Parallel computing with recursive function

My challenge is to parallel compute a recursive function. 我的挑战是并行计算递归函数。 However, the recursion is quite deep, and therefore (in my own novice words) there is an issue with allocating a worker when all the workers are busy. 但是,递归非常深,因此(用我自己的新手来讲)在所有工作人员都忙时分配工作人员存在问题。 in short, it crushes. 简而言之,它粉碎了。

Here is some reproducible code. 这是一些可复制的代码。 The code is very stupid, but the structure is what counts. 代码非常愚蠢,但是结构才是最重要的。 This is a simplified version of what is going on. 这是正在发生的事情的简化版本。

I work on a windows machine, if the solution is to go linux, just say the word. 我在Windows机器上工作,如果解决方案是使用linux,请说一句话。 Because the real function can be quite deep, managing the number of workers that are called for in the upper level will not solve the issue. 由于实际功能可能很深,因此在上层管理所需的工作人员数量将无法解决问题。 Is there perhaps a way to know in what level the recursion is? 也许有一种方法可以知道递归处于哪个级别?

  FUN <- function(optimizer,neighbors,considered,x){
    considered <- c(considered,optimizer)
    neighbors <- setdiff(x=neighbors,y=considered)

    if (length(neighbors)==0) {
      # this loop is STUPID, but it is just an example.
      z <- numeric(10)
      for (i in 1:100)
      {
        z[i] <- sample(x,1)
      } 
      return(max(z)) 
    } else {
      # Something embarrassingly parallel, 
      # but cannot be vectorized.
      z <- numeric(10)
      z <- foreach(i=1:10, .combine='c') %dopar%{
        FUN(optimizer=neighbors[1],neighbors=neighbors,
                  considered=considered,x=x)}
    return(max(z))
    }
}

require(doParallel,quietly=T)
cl <- makeCluster(3)
clusterExport(cl, c("FUN"))
registerDoParallel(cl)
getDoParWorkers()



>FUN(optimizer=1,neighbors=c(2),considered=c(),x=1:500)
[1] 500
>FUN(optimizer=1,neighbors=c(2,3),considered=c(),x=1:500)
Error in { : task 1 failed - "could not find function "%dopar%""
>FUN(optimizer=1,neighbors=c(2,3),considered=c(),x=1:500)
Error in { : task 1 failed - "could not find function "%dopar%""

Is this error really because the recursion is too deep or is it just because you haven't got require(doParallel) in your FUN function? 这个错误是真的因为递归太深还是仅仅是因为您的FUN函数中没有require(doParallel)吗? So that when FUN is called on the workers, that instance of R hasn't got that package in its list. 因此,当在工作程序上调用FUN时,R的实例未在其列表中包含该程序包。

Your first example doesn't do this because its simple enough to not get to the inner %dopar% loop. 您的第一个示例不执行此操作,因为它很简单,无法进入内部%dopar%循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM