Is there any way to break out of a foreach loop?

前端 未结 6 1189
耶瑟儿~
耶瑟儿~ 2020-12-04 22:29

I am using the R package foreach() with %dopar% to do long (~days) calculations in parallel. I would like the ability to stop the entire set of cal

6条回答
  •  感情败类
    2020-12-04 23:22

    It's not a direct answer to your question, but using when() you can avoid entering the loop if a condition is satisfied:

    x <- foreach(k = 1:10, .combine="cbind", .errorhandling="stop") %:%
      when( !is.element(k, 2:6) ) %do%
      {
        cat("Element ", k, "\n")
        Sys.sleep(0.5)
        k
      }
    

    EDIT:

    I forgot something: I think it's by design, that you cannot just stop the foreach loop. If you run the loop in parallel, each turn is processed independently, which means when you stop the entire loop for k=2 it is not predictable if the process for k=1 terminated already or is still running. Hence, using the when() condition gives you a deterministic result.

    EDIT 2: Another solution considering your comment.

    shouldStop <- FALSE
    x <- foreach(k = 1:10, .combine="cbind", .errorhandling="stop") %do%
      {
        if( !shouldStop ){
          # put your time consuming code here
          cat("Element ", k, "\n")
          Sys.sleep(0.5)
          shouldStop <- shouldStop ||  is.element(k, 2:6)
          k
        }
      }
    

    Using this solution, the processes which are running while the stop condition becomes true are still calculated to an end, but you avoid time consumption on all upcoming processes.

提交回复
热议问题