diff --git a/NEWS.md b/NEWS.md index f94c670ae7..9582060a5e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -36,6 +36,7 @@ 9. New `frollmean` has been added to calculate _rolling mean_. Function name and arguments are experimental. Related to [#2778](https://github.com/Rdatatable/data.table/issues/2778) (and [#624](https://github.com/Rdatatable/data.table/issues/624), [#626](https://github.com/Rdatatable/data.table/issues/626), [#1855](https://github.com/Rdatatable/data.table/issues/1855)). Other rolling statistics will follow. +10. `setDTthreads()` gains `restore_after_fork=`, [#2885](https://github.com/Rdatatable/data.table/issues/2885). The default `NULL` leaves the internal option unchanged which by default is `TRUE`. `data.table` has always switched to single-threaded mode on fork. It used to restore multi-threading after a fork too but problems were reported on Mac and Intel OpenMP library (see 1.10.4 notes below). We are trying again thanks to suggestions and success reported by Kun Ren and Mark Klik in package `fst`. If you experience problems will multi threading after a fork, please restart R and call `setDTthreads(restore_after_fork=FALSE)`. #### BUG FIXES diff --git a/R/openmp-utils.R b/R/openmp-utils.R index aa4a965064..b6776e73db 100644 --- a/R/openmp-utils.R +++ b/R/openmp-utils.R @@ -1,5 +1,5 @@ -setDTthreads <- function(threads) { - invisible(.Call(CsetDTthreads, as.integer(threads))) +setDTthreads <- function(threads=0, restore_after_fork=NULL) { + invisible(.Call(CsetDTthreads, as.integer(threads), restore_after_fork)) } getDTthreads <- function(verbose=getOption("datatable.verbose", FALSE)) { diff --git a/inst/tests/tests.Rraw b/inst/tests/tests.Rraw index 026563a03f..30c9ec26d5 100644 --- a/inst/tests/tests.Rraw +++ b/inst/tests/tests.Rraw @@ -12875,8 +12875,7 @@ test(1963.7, shift(DT, -1:1), c(9L, 8L, 7L, 6L, 5L, 4L, 3L, 2L, 1L, NA), 10:1, c(NA, 10L, 9L, 8L, 7L, 6L, 5L, 4L, 3L, 2L))) ## some coverage tests for good measure -test(1963.8, shift(DT$x, type = 'some_other_type'), - error = 'should be one of "lag"') +test(1963.8, shift(DT$x, type = 'some_other_type'), error='should be one of.*lag.*lead') test(1963.9, shift(c(1+3i, 2-1i)), error = 'Unsupported type') # 0 column data.table should not have rownames, #3149 diff --git a/man/openmp-utils.Rd b/man/openmp-utils.Rd index 95e3be0dec..7a88460886 100644 --- a/man/openmp-utils.Rd +++ b/man/openmp-utils.Rd @@ -3,20 +3,24 @@ \alias{getDTthreads} \title{ Set or get number of threads that data.table should use } \description{ -Set and get number of threads to be used in \code{data.table} functions that are parallelized with OpenMP. Default value 0 means to utilize all CPU available with an appropriate number of threads calculated by OpenMP. \code{getDTthreads()} returns the number of threads that will be used. This affects \code{data.table} only and does not change R itself or other packages using OpenMP. The most common usage expected is \code{setDTthreads(1)} to limit \code{data.table} to one thread for pre-existing explicitly parallel user code; e.g. via packages parallel and foreach. Otherwise, nested parallelism may bite. As \code{data.table} becomes more parallel automatically internally, we expect explicit user parallelism to be needed less often. - -Attempting to \code{setDTthreads()} to more than the number of logical CPUs is intended to be ineffective; i.e., \code{getDTthreads()} will still return the number of logical CPUs in that case. Further, there is a hard coded limit of 1024 threads (with warning when imposed) to prevent accidentally picking up the value of \code{INT_MAX} (2 billion; i.e. unlimited) from \code{omp_get_thread_limit()}. We have followed the advice of section 1.2.1.1 in the R-exts manual: "\ldots or, better, for the regions in your code as part of their specification\ldots num_threads(nthreads)\ldots That way you only control your own code and not that of other OpenMP users." All the parallel region in data.table contain this directive. This is mandated by a \code{grep} in the package's quality control release procedure script. +Set and get number of threads to be used in \code{data.table} functions that are parallelized with OpenMP. Default value 0 means to utilize all CPU available with an appropriate number of threads calculated by OpenMP. \code{getDTthreads()} returns the number of threads that will be used. This affects \code{data.table} only and does not change R itself or other packages using OpenMP. We have followed the advice of section 1.2.1.1 in the R-exts manual: "\ldots or, better, for the regions in your code as part of their specification\ldots num_threads(nthreads)\ldots That way you only control your own code and not that of other OpenMP users." All the parallel region in data.table contain this directive. This is mandated by a \code{grep} in data.table's quality control CRAN release procedure script. } \usage{ -setDTthreads(threads) +setDTthreads(threads = 0, restore_after_fork = NULL) getDTthreads(verbose = getOption("datatable.verbose", FALSE)) } \arguments{ \item{threads}{ An integer >= 0. Default 0 means use all CPU available and leave the operating system to multi task. } - \item{verbose}{ Display the value returned by some OpenMP function calls. } + \item{restore_after_fork}{ Should data.table be multi-threaded after a fork has completed? NULL leaves the current setting unchanged which by default is TRUE. See details below. } + \item{verbose}{ Display the value of some OpenMP settings, including the restore_after_fork internal option. } } \value{ -A length 1 \code{integer}. The old value is returned by \code{setDTthreads} so you can store that value and pass it to \code{setDTthreads} again after the section of your code where you, probably, limited to one thread. +A length 1 \code{integer}. The old value is returned by \code{setDTthreads} so you can store that prior value and pass it to \code{setDTthreads()} again after the section of your code where you control the number of threads. +} +\details{ + \code{data.table} automatically switches to single threaded mode upon fork (the mechanism used by \code{\link[parallel]{mclapply}} and the foreach package). Otherwise, nested parallelism would very likely overload your CPUs and result in much slower execution. As \code{data.table} becomes more parallel internally, we expect explicit user parallelism to be needed less often. The \code{restore_after_fork} option controls what happens after the explicit fork parallelism completes. It needs to be at C level so it is not a regular R option using \code{options()}. By default \code{data.table} will be multi-threaded again; restoring the prior setting of \code{getDTthreads()}. But problems have been reported in the past on Mac and Intel OpenMP libraries, whereas success has been reported on Linux. If you experience problems after fork, start a new R session and change the default behaviour by calling \code{setDTthreads(restore_after_fork=FALSE)} before retrying. Please raise issues on the data.table GitHub issues page. + + Attempting to \code{setDTthreads()} to more than the number of logical CPUs is intended to be ineffective; i.e., \code{getDTthreads()} will still return the number of logical CPUs in that case. Further, there is a hard coded limit of 1024 threads (with warning when imposed) to prevent accidentally picking up the value \code{INT_MAX} (2 billion; i.e. unlimited) which we have seen returned by OpenMP's \code{omp_get_thread_limit()} in some cases. } \keyword{ data } diff --git a/src/openmp-utils.c b/src/openmp-utils.c index 3deba95303..824b109395 100644 --- a/src/openmp-utils.c +++ b/src/openmp-utils.c @@ -16,9 +16,8 @@ * avoid the deadlock/hang (#1745 and #1727) and return to prior state afterwards. */ -static int DTthreads = 0; -// Never read directly, hence static. Always go via getDTthreads() and check that in -// future using grep's in CRAN_Release.cmd +static int DTthreads = 0; // Never read directly, hence static; always go via getDTthreads(). +static bool RestoreAfterFork = true; // see #2885 in v1.12.0 int getDTthreads() { #ifdef _OPENMP @@ -44,6 +43,7 @@ SEXP getDTthreads_R(SEXP verbose) { Rprintf("omp_get_max_threads() = %d\n", omp_get_max_threads()); Rprintf("omp_get_thread_limit() = %d\n", omp_get_thread_limit()); // can be INT_MAX meaning unlimited Rprintf("DTthreads = %d\n", DTthreads); + Rprintf("RestoreAfterFork = %s\n", RestoreAfterFork ? "true" : "false"); #ifndef _OPENMP Rprintf("This installation of data.table has not been compiled with OpenMP support.\n"); // the omp_ functions used above are defined in myomp.h to be 1 in this case @@ -52,21 +52,24 @@ SEXP getDTthreads_R(SEXP verbose) { return ScalarInteger(getDTthreads()); } -SEXP setDTthreads(SEXP threads) { +SEXP setDTthreads(SEXP threads, SEXP restore_after_fork) { if (!isInteger(threads) || length(threads) != 1 || INTEGER(threads)[0] < 0) { // catches NA too since NA is -ve - error("Argument to setDTthreads must be a single integer >= 0. \ - Default 0 is recommended to use all CPU."); + error("threads= must be a single integer >= 0. Default 0 is recommended to use all CPU."); + } + if (!isNull(restore_after_fork) && !(isLogical(restore_after_fork) && LOGICAL(restore_after_fork)[0]>=0 /*not NA*/)) { + error("restore_after_fork= must be TRUE or FALSE. The default NULL means leave the current setting unchanged. getDTthreads(verbose=TRUE) reports the current setting.\n"); } int old = DTthreads; DTthreads = INTEGER(threads)[0]; - // Do not call omp_set_num_threads() here, and particularly not to omp_get_thread_limit() // which is likely INT_MAX (unlimited). Any calls to omp_set_num_threads() affect other // packages and R itself too which has some OpenMP usage. Instead we set our own DTthreads // static global variable, read that from getDTthreads() and ensure num_threads(getDTthreads()) // directive is always present via the grep in CRAN_Release.cmd. + if (!isNull(restore_after_fork)) RestoreAfterFork = LOGICAL(restore_after_fork)[0]; + return ScalarInteger(old); } @@ -79,6 +82,8 @@ SEXP setDTthreads(SEXP threads) { fork completes. But now in an attempt to alleviate problems propogating (likely Intel's OpenMP only) we now leave data.table in single-threaded mode after parallel's fork. User can call setDTthreads(0) to return to multi-threaded as we do in tests on Linux. + [UPDATE] in v1.12.0 we're trying again to RestoreAferFork (#2285) with optional-off due to success + reported by Ken Run and Mark Klik in fst#110 and fst#112 DO NOT call omp_set_num_threads(1) inside when_fork()!! That causes a different crash/hang on MacOS upon mclapply's fork even if data.table is merely loaded and neither used yet in the session nor by @@ -90,14 +95,21 @@ SEXP setDTthreads(SEXP threads) { on MacOS. */ +static int pre_fork_DTthreads = 0; + void when_fork() { + pre_fork_DTthreads = DTthreads; DTthreads = 1; } +void after_fork() { + if (RestoreAfterFork) DTthreads = pre_fork_DTthreads; +} + void avoid_openmp_hang_within_fork() { // Called once on loading data.table from init.c #ifdef _OPENMP - pthread_atfork(&when_fork, NULL, NULL); + pthread_atfork(&when_fork, &after_fork, NULL); #endif }