Mislav
Mislav

Reputation: 1563

Do something only in firs step of for loop in parallel

I would like to execute commands in first step of for loop and other list of commands in all steps of the same for loop. It is easy to do that in non-paralel loop:

for (i in 1:5) {
  if (i == 1) {
    print("First step")
  }
  print("Same code")
}

but I would like to execute for loop in parallel, that is write foreach loop, which means i would not be equal to 1 for all nodes (processes). Non-paralell foreach loop is:

library(foreach)
foreach(i = 1:5) %do% {
  if (i == 1) {
    print("First step")
  }
  print("Same code")
}

How to execute print("First") in only first step for every node?

Upvotes: 1

Views: 41

Answers (1)

F. Privé
F. Privé

Reputation: 11728

You can do:

library(doParallel)
registerDoParallel(cl <- makeCluster(3, outfile = ""))
do_print <- TRUE
foreach(i = 1:5) %dopar% {
  if (do_print) {
    print("First step")
    do_print <- FALSE
  }
  print("Same code")
}
stopCluster(cl)

Upvotes: 1

Related Questions