R中foreach循环中的所有并行进程生成相同的结果

All parallel processes in foreach loop in R generating same results

我使用 foreach() 循环并行生成随机数组。但是我在所有并行过程中得到了相同的结果。如何在每个并行进程中添加随机性,使每个进程彼此不同?

library(doFuture)
library(foreach)

# Parallel programming
registerDoFuture()
plan(multicore, workers = 3)


res = foreach(iter = 1:3) %dopar%
{
  
  # generate random array
  x = runif(n = 5)
  
}

并行生成的所有数组都相同

> res
[[1]]
[1] 0.55882648 0.73863525 0.51284839 0.01454722 0.08909375

[[2]]
[1] 0.55882648 0.73863525 0.51284839 0.01454722 0.08909375

[[3]]
[1] 0.55882648 0.73863525 0.51284839 0.01454722 0.08909375

如果我们运行 OP 的代码

,则有警告消息建议使用doRNG 包中的%dorng%

Warning messages: 1: UNRELIABLE VALUE: One of the foreach() iterations (‘doFuture-1’) unexpectedly generated random numbers without declaring so. There is a risk that those random numbers are not statistically sound and the overall results might be invalid. To fix this, use '%dorng%' from the 'doRNG' package instead of '%dopar%'. This ensures that proper, parallel-safe random numbers are produced via the L'Ecuyer-CMRG method. To disable this check, set option 'future.rng.onMisuse' to "ignore". ...

因此,加载包并使用 %dorng% 代替 %dopar%

library(doFuture)
library(foreach)
library(doRNG)

# Parallel programming
registerDoFuture()
plan(multicore, workers = 3)

res = foreach(iter = 1:3) %dorng%
 {
   # generate random array
   x = runif(n = 5)
 }
res
[[1]]
[1] 0.1058127 0.4715034 0.9921409 0.3633179 0.9830486

[[2]]
[1] 0.2801489 0.1372907 0.6491732 0.6267578 0.1657053

[[3]]
[1] 0.8981384 0.8950956 0.4003182 0.9338281 0.9706626
attr(,"rng")
attr(,"rng")[[1]]
[1]       10407    41337137 -1038536386  -420834137  1745650876  2038421133 -1613694998

attr(,"rng")[[2]]
[1]       10407 -1775499178   -92726601 -1608089308   992801654   241903385  2115481412

attr(,"rng")[[3]]
[1]       10407  1979572086 -1800896478  -210258865   856919030   298818868  1787849826