R/parallel.R

Defines functions .parallel_lapply .validate_n_cores

.validate_n_cores <- function(n_cores) {
  if (!is.numeric(n_cores) || length(n_cores) != 1L || is.na(n_cores) ||
      !is.finite(n_cores) || n_cores < 1 || n_cores != as.integer(n_cores)) {
    stop("n_cores must be one positive integer.", call. = FALSE)
  }
  as.integer(n_cores)
}

.parallel_lapply <- function(X, FUN, n_cores = 1L, ...) {
  n_cores <- .validate_n_cores(n_cores)
  if (length(X) < 2L || n_cores == 1L) return(lapply(X, FUN, ...))
  workers <- min(n_cores, length(X))

  if (.Platform$OS.type == "windows") {
    cluster <- parallel::makeCluster(workers)
    on.exit(parallel::stopCluster(cluster), add = TRUE)
    return(parallel::parLapply(cluster, X, FUN, ...))
  }

  answer <- parallel::mclapply(
    X, FUN, ..., mc.cores = workers, mc.preschedule = TRUE,
    mc.set.seed = TRUE
  )
  failed <- vapply(answer, inherits, logical(1), what = "try-error")
  if (any(failed)) {
    detail <- sub("^[^:]*:[[:space:]]*", "", as.character(
      answer[[which(failed)[[1L]]]]))
    stop("Parallel worker failed: ", detail, call. = FALSE)
  }
  answer
}

Try the NEArender package in your browser

Any scripts or data that you put into this service are public.

NEArender documentation built on Nov. 28, 2026, 5:10 p.m.