我尝试设置一个可以重用的函数,不需要添加不经常使用的全局变量。但是,该功能无法实现我期望的效果。
基本上,我只使用两个函数,即mclapply和parLapply。这两个功能均无法正常运行。
这是我尝试构建的功能
multi_task <- function(func){
function(...){
if(.Platform$OS.type == 'windows'){
cl <- makePSOCKcluster(detectCores())
clusterExport(cl,c(), envir = environment())
} else if(.Platform$OS.type == 'unix'){
cl <- makeCluster(detectCores(), type = "FORK")
}
value <- match.fun(func)(..., if("cl" %in% names(as.list(func)))cl = cl)
return(value)
stopCluster(cl)
gc()
}
}
当我尝试parLapply
target <- multi_task('parLapply')(x, Fun)
,我希望它将创建足够的簇并返回该值。而是显示Error in defaultCluster(cl) : no cluster 'cl' supplied and none is registered
,而当我尝试mclapply时,我得到Error in checkCluster(cl) : not a valid cluster
。
如果我只是一步一步来
cl <- makeCluster(detectCores(), type = "FORK")
t <- parLapply(x,Fun)
stopCluster()
然后不会发生任何错误。建立群集是否有任何限制,或者与环境有关?