Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doParallelMC could not treat global variable correctly. #6

Open
Neutron3529 opened this issue Aug 19, 2022 · 1 comment
Open

doParallelMC could not treat global variable correctly. #6

Neutron3529 opened this issue Aug 19, 2022 · 1 comment

Comments

@Neutron3529
Copy link

the following code return the correct result

p1=function(x)x+ONE
doParallel::registerDoParallel(parallel::makeForkCluster(2)) # register doParallelSNOW
foreach::`%dopar%`(foreach::foreach(i=1:5) , {ONE=1;p1(i)})

but if we change parallel::makeForkCluster(2) to 2, it generate an error, Error in { : task 1 failed - "object 'ONE' not found"

p1=function(x)x+ONE
doParallel::registerDoParallel(2) # register doParallelMC
foreach::`%dopar%`(foreach::foreach(i=1:5) , {ONE=1;p1(i)})

the root cause it that, doParallelMC calls mclapply directly, which create an extra environmnet and thus failed to execute. minimal example:

f=function(x)x+ONE
g=function(y){
    ONE=1 # here, ONE is assigned in g's environment, not the global environment
    f(y) # here, f would search ONE firstly in its closure, and then search it directly in the global environment, thus it could not found `ONE` which is defined in g's environment.
}
g(1) # could not found ONE
y=1
eval(body(g)) # we could solve the question by eval body here.

Should there be some document about this thing?

@Sherry520
Copy link

Your function should change to

p1=function(x,ONE)x+ONE

To use it, p1(x=i,ONE=1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants