2
votes

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.

1
You should convert your edit to an answer so that it's easy to find and understand.bright-star
Done (see answer below)Marcelo

1 Answers

1
votes

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)