一个R函数范围和并行

问题描述:

考虑下面的函数定义一个R函数范围和并行

library(doParallel) 
f_print <- function(x) 
{ 
    print(x) 
} 
f_foreach <- function(l) 
{ 
    foreach (i=l) %do% 
    { 
    f_print(i) 
    } 
} 

f_foreach_parallel <- function(l) 
{ 
    doParallel::registerDoParallel(1) 
    foreach (i=l) %dopar% 
    { 
    f_print(i) 
    } 
} 

功能用途:

> f_foreach(c(1,2)) 
[1] 1 
[1] 2 
[[1]] 
[1] 1 

[[2]] 
[1] 2 

> f_foreach_parallel(c(1,2)) 
Show Traceback 

Rerun with Debug 
Error in { : 
    task 1 failed - "impossible de trouver la fonction "f_print"" 
    [Error: could not find function f_print] 
> 

你可以帮助解释为什么当并行参与foreachf_print()是不可见的?我们如何在这个并行的foreach中使用f_print()?与此有关的任何文件?

+0

第二个函数适用于我,没有错误。我正在运行R 3.4.2中每个包的最新版本(doParallel 1.0.11和foreach 1.4.3)。 – lmo

+0

这是令人困惑的。我使用的是doParallel_1.0.10和foreach_1.4.3。我刚刚更新到与您的相同的最新版本,问题仍然存在。有什么想法吗 ? – Kenny

+1

这很奇怪。我只是用一个新版本的R重新运行代码,并没有得到一个错误。你在Windows上工作吗?如果是这样,有一些可能性,你将不得不导出像这样的函数:'foreach(i = 1,.export = c(“f_print”))%dopar%'。如果这能起作用,那么这个问题与'snow'和'mcapply'之间的区别在于所有操作系统的第一个作品,而第二个作品只能在* nix的作品中出现。我正在运行openSuse linux。 – lmo

除了那些已经被在顶帖,特别是在指定.export之一的评论说,使用doFuture包时,你的代码确实无论并行工作的后端,操作系统和.export的。这是你设置的改编版:

f_print <- function(x) { 
    print(x) 
} 

f_foreach <- function(l) { 
    foreach(i=l) %do% { 
    f_print(i) 
    } 
} 

f_foreach_dopar <- function(l) { 
    foreach(i=l) %dopar% { 
    f_print(i) 
    } 
} 

而不是做:

library("doParallel") 

## Setup PSOCK workers (just as on Windows) 
workers <- parallel::makeCluster(1L, outfile = "") 
registerDoParallel(workers) 

f_foreach_dopar(c(1,2)) 
## Error in { : task 1 failed - "could not find function "f_print"" 

,你可以这样做:

library("doFuture") 
registerDoFuture() 

## As above 
workers <- parallel::makeCluster(1L, outfile = "") 
plan(cluster, workers = workers) 

f_foreach_dopar(c(1,2)) 
## [1] 1 
## [1] 2 
## [[1]] 
## [1] 1 
## 
## [[2]] 
## [1] 2 

之所以出现这种工作原理是,doFuture做更彻底的搜索以确定全局变量(此处为f_print())。

PS。 outfile = ""的原因是,实际显示stdout/stderr输出(例如从print())。在并行处理中重定向stdout/stderr(我不建议这么做)是一个完全不同的讨论,但我会假设您仅使用print()作为例子。