我有一个奇怪的情况,使用foreach
串行和并行后端在我第一次调用时会给出不同的结果,但后来两个结果都匹配。我曾经RNG
使结果可重复seed
下面是一个解释场景的示例函数:
func <- function(ncores = NULL, seed = 1234){
if (!is.null(ncores)){ # this block registers for parallel backend
cl <- makeCluster(ncores)
registerDoParallel(cl)
registerDoRNG(seed, once = TRUE)
on.exit(stopCluster(cl))
} else { # this block registers for serial computation
registerDoSEQ()
registerDoRNG(seed, once = TRUE)
}
w = foreach(i = 1:10, .combine = 'c') %dorng% {
mean(sample(1:100, 50, replace = TRUE))
}
attr(w, "rng") <- NULL
return(w)
}
# first time running below 2 lines
# case 1 : serial
w1 <- func(ncores = NULL)
# Case 2 : parallel
w2 <- func(ncores= 5)
identical(w1, w2)
# second time running below 2 lines
# case 1: serial
w3 <- func(ncores = NULL)
# case 2: parallel
w4 <- func(ncores= 5)
identical(w1, w2)
# [1] FALSE
identical(w3, w4)
# [1] TRUE
注册顺序过程时我错过了什么吗?