From b61d495109be79bd02d4172d7570f28a2920c652 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Paul-Christian=20B=C3=BCrkner?= Date: Mon, 27 May 2024 19:17:11 +0200 Subject: [PATCH] fix issue #1658 --- DESCRIPTION | 2 +- NEWS.md | 3 +++ R/misc.R | 17 ++++++++++------- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 34a7f2ea5..8cdfd9570 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -2,7 +2,7 @@ Package: brms Encoding: UTF-8 Type: Package Title: Bayesian Regression Models using 'Stan' -Version: 2.21.4 +Version: 2.21.5 Date: 2024-05-27 Authors@R: c(person("Paul-Christian", "Bürkner", email = "paul.buerkner@gmail.com", diff --git a/NEWS.md b/NEWS.md index 1566163a5..3ddffe64f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -8,6 +8,9 @@ * Fix a bug that led to partially duplicated Stan code in multilevel terms thanks to Henrik Singmann. (#1651) +* Fix problems with parallel executions of post-processing functions +sometimes leaving unused R instances behind. Thanks to Andrew Johnson, +Aki Vehtari, and Noa Kallioinen. (#1658) ### Other Changes diff --git a/R/misc.R b/R/misc.R index 00ef9a150..2da709f1b 100644 --- a/R/misc.R +++ b/R/misc.R @@ -425,13 +425,16 @@ plapply <- function(X, FUN, cores = 1, ...) { if (cores == 1) { out <- lapply(X, FUN, ...) } else { - if (!os_is_windows()) { - out <- parallel::mclapply(X = X, FUN = FUN, mc.cores = cores, ...) - } else { - cl <- parallel::makePSOCKcluster(cores) - on.exit(parallel::stopCluster(cl)) - out <- parallel::parLapply(cl = cl, X = X, fun = FUN, ...) - } + cl_type <- ifelse(os_is_windows(), "PSOCK", "FORK") + cl <- parallel::makeCluster(cores, type = cl_type) + # Register a cleanup for the cluster in case the function fails + # Need to wrap in a tryCatch to avoid error if cluster is already stopped + on.exit(tryCatch( + { parallel::stopCluster(cl) }, + error = function(e) invisible(NULL) + )) + out <- parallel::parLapply(cl = cl, X = X, fun = FUN, ...) + parallel::stopCluster(cl) } out }