简体   繁体   中英

R in parallel using doMC library: How to reuse cores for subsequent parallel processes?

When running the following script in R:

library(doMC)
registerDoMC(cores=3)

# First foreach
# This runs in 3 threads
foreach(i=1:3) %dopar% sqrt(i)

# Second foreach 
# This add 3 threads to the previous ones (now inactive but still consuming memory), totalling 6 threads
foreach(i=1:3) %dopar% sqrt(i)

I would like to know how to reuse the threads of the first foreach when running the second one, so that the whole script always runs using 3 cores.

Thanks to the suggestion of one of doMC's developers, I could find a workaround. Using a different library, the following code does what I was looking for:

library(doParallel)
cores=makeForkCluster(3)
registerDoParallel(cores)

# First foreach
# This runs in 3 threads
foreach(i=1:3) %dopar% sqrt(i)

# Second foreach 
# This reuses the previous 3 threads (total of 3 active threads)
foreach(i=1:3) %dopar% sqrt(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM