7.6 External Libraries with Their Own Threads
7.6.1 Motivation
R does not do its own dense linear algebra. Matrix products and decompositions call BLAS (Basic Linear Algebra Subprograms) and LAPACK (Linear Algebra Package). Optimized builds of these libraries, such as OpenBLAS and Intel MKL, are multithreaded and start their own threads to split the work.
OpenMP is a common threading API for C and Fortran. Many R packages use OpenMP to parallelize their computation. When a package’s code enters an OpenMP parallel region, the OpenMP runtime starts a team of threads, or reuses one it started earlier.
This creates a problem. If R is also multithreaded, and external libraries are also multithreaded, the total thread count can explode. Eight R workers on an eight-core machine, each running a BLAS that starts eight threads, make 64 threads, before any package’s OpenMP code adds its own.
This is called oversubscription. Too many threads compete for too few cores, and the cores spend time switching between threads instead of computing.
7.6.2 External libraries in the R runtime
Many R installations, especially on Linux, replace R’s reference BLAS with OpenBLAS or Intel MKL. Both are multithreaded by default.
When R code calls matrix multiplication:
C <- A %*% BFor two double matrices with no NA, NaN or Inf values, R hands this to DGEMM (double-precision general matrix multiply) in BLAS, or to DGEMV when one side is a single row or column. If BLAS is multithreaded, it starts threads to parallelize the multiply.
OpenBLAS and MKL both default to roughly one thread per core, so on an eight-core machine a single multiply can use eight threads.
GNU R ships with its own reference BLAS, which is single-threaded. A threaded BLAS arrives when someone puts it there: some Linux distributions build R against an optimized BLAS, and users swap the library themselves. Once one is in place it reads OMP_NUM_THREADS or its own variable, and with nothing set it usually takes every core it can see.
Many user packages also use OpenMP:
#pragma omp parallel for
for (int i = 0; i < n; i++) {
result[i] = expensive_computation(data[i]);
}When this loop executes, OpenMP spawns threads. The number is controlled by OMP_NUM_THREADS or by the package’s explicit configuration.
7.6.3 Interaction with R-level workers
Suppose you use the parallel package to run code on eight cores:
library(parallel)
result <- mclapply(1:100, function(i) sum(crossprod(matrix(rnorm(1e6), 1000))),
mc.cores = 8)This starts eight R worker processes (via fork on Unix). Each worker is a complete R interpreter. Each worker runs crossprod(), which calls BLAS.
If BLAS is configured to use eight threads, each worker spawns eight BLAS threads. The total thread count is:
- Eight worker processes (conceptually one thread each at the OS level, but each is a full interpreter)
- Eight BLAS threads per worker
- Total: 64 threads competing for eight cores
This is severe oversubscription. Each core has eight runnable threads, so context switches eat into the gain, and the speedup falls short of what eight cores could give.
7.6.4 Thread count control
The primary tool for controlling BLAS threads is the environment variable OMP_NUM_THREADS:
export OMP_NUM_THREADS=1Setting OMP_NUM_THREADS=1 tells an OpenMP-based BLAS, MKL, and OpenMP code in packages to use a single thread. OpenBLAS and MKL check their own OPENBLAS_NUM_THREADS and MKL_NUM_THREADS first. Computation within each worker is sequential but avoids oversubscription.
OpenBLAS reads its variables once, at startup, and “Writing R Extensions” warns that OpenMP variables may need to be set “outside the R process or before any use of OpenMP”. A BLAS linked into R loads when R starts, so for that BLAS the variable has to be set before the R process starts. From R code, that means setting it before starting workers that are new processes:
Sys.setenv(OMP_NUM_THREADS = 1, OPENBLAS_NUM_THREADS = 1)
library(parallel)
cl <- makeCluster(8)
result <- parLapply(cl, 1:100, function(i) sum(crossprod(matrix(rnorm(1e6), 1000))))
stopCluster(cl)Each PSOCK worker is a fresh R process that inherits the variables, so its BLAS starts with one thread. Total thread count: eight. The same call does not help mclapply(): forked workers inherit the parent’s BLAS, which read its settings when the parent R started.
But this is manual. Users must know to do it. If they do not, performance suffers silently.
Some BLAS implementations provide API calls to change the thread count at runtime:
mkl_set_num_threads(1); // Intel MKL
omp_set_num_threads(1); // OpenMP
openblas_set_num_threads(1); // OpenBLASBut these are not portable. Not every BLAS library provides them. And the calls must be made from the correct context: omp_set_num_threads() applies to parallel regions started from the calling thread, and MKL has a separate per-thread call, mkl_set_num_threads_local().
BLAS thread count control varies by implementation. There is no standard, portable way to query or change thread counts from R code. Users must rely on environment variables or library-specific APIs.
7.6.5 Behavior across fork
Unix provides the fork() system call. A process forks into two processes: a parent and an identical child. The child is a complete copy of the parent’s memory.
When a multithreaded process forks, the child gets only the calling thread. The other threads do not exist in the child. Mutexes and condition variables are copied in whatever state they were in at the moment of the fork.
This is a major pitfall. If a BLAS thread held a lock when the process forked, the child’s copy of that lock stays held, because the thread that would release it is not there. Any code in the child that tries to acquire that lock deadlocks.
A library can register handlers with pthread_atfork() to clean up around a fork. OpenBLAS, built with its own thread pool, registers one that shuts the pool down before the fork, so the child starts a fresh pool on its first threaded call. Its source notes that a build on GNU OpenMP can still hang after a fork, and not every library registers a handler at all.
The parallel package’s mclapply() uses fork on Unix. A BLAS thread pool in the parent does not exist in the child; what the child inherits is the library’s memory, including its thread-count setting. With OpenBLAS’s pthreads build, the fork handler has shut the pool down, and the child’s first threaded call starts a new one with the inherited count.
For the sunlight project, which uses a prewarmed forkserver:
library(sunlight)
pool <- hatch(8, preload = "Matrix")
result <- pmap(pool, 1:100, function(i) sum(crossprod(matrix(rnorm(1e6), 1000))))
shutdown(pool)The forkserver preloads packages and data into a template process. The template forks the workers. sunlight starts the template with OPENBLAS_NUM_THREADS, OMP_NUM_THREADS and MKL_NUM_THREADS set to 1, so the template has no BLAS pool when it forks, and it warns if a preloaded package has started a thread of its own. After the fork, hatch() calls govern(), which gives each worker’s BLAS, OpenMP and data.table a fair share of the cores: the core count divided by the number of workers, and at least one. A library that reads its thread count once at load, as OpenBLAS does, takes the new count only through the RhpcBLASctl package, which sunlight calls when it is installed.
Copy-on-write keeps little of the template’s memory shared, because a garbage collection in a worker writes mark bits, and a full collection privatizes most of the pages it inherited. Fork, copy-on-write, and the first GC has the measurement and its caveats.
7.6.6 Interaction with R’s threading model
threaded-r introduces a new constraint: multiple R interpreters in the same process. If one interpreter calls a multithreaded BLAS and another interpreter also calls it, both use the same BLAS thread pool.
The BLAS library and its thread pool are process-global, so the threads are shared across interpreters and thread count control becomes tricky.
Setting OMP_NUM_THREADS from one interpreter does nothing to a BLAS that has already loaded. The runtime calls do work, and they are process-wide: if interpreter A calls openblas_set_num_threads(4) and interpreter B then calls it with 2, the second call wins for both, because OpenBLAS keeps one global count. Both interpreters then compete for the same thread pool.
This is why threaded-r with multiple interpreters needs careful coordination of BLAS thread counts.
Possible solutions include: (1) pin each interpreter to a core subset and set BLAS threads accordingly, or (2) use per-thread BLAS implementations (expensive and rare). A third option is to serialize BLAS calls across interpreters, but this defeats parallelism.
7.6.7 Surprising thread counts
Users often see unexpectedly high thread counts when running parallel R code:
# count the threads of one R process, by pid
ps -o nlwp= -p "$R_PID"
# or list them
ps -eLo pid,tid,comm | awk '$3 == "R"'They see 64 threads when they expected eight.
The reason is oversubscription: eight worker processes, each using eight BLAS threads. This is the default behavior. The user did not explicitly configure threads. The environment just stacks them.
Users who do not understand BLAS multithreading are surprised. They expect R to use eight threads for eight cores. But R is not the only source of threads.
Tools also count differently. top shows one row per process by default, on Linux and on macOS, while Linux’s ps -eLo and top -H show one row per thread. Users get confused when the same code shows different counts on different machines.
7.6.8 Controlling threads at the R level
Base R has no call for this. RcppParallel ships one for the pool it manages:
RcppParallel::setThreadOptions(numThreads = 1)That setting reaches RcppParallel’s own workers and nothing else. A threaded BLAS underneath will keep whatever thread count it was given.
For BLAS, the usual route is to set environment variables before starting R:
export OMP_NUM_THREADS=1
ROr via Sys.setenv(), which reaches R processes started afterwards and libraries loaded afterwards, but not a BLAS that loaded when R started:
Sys.setenv(OMP_NUM_THREADS = 1)These tools exist but are not well-integrated. Users must know about them, and none of them is automatic.
Further reading
- OpenMP 5.0 specification <https://www.openmp.org/spec-html/5.0/openmpch6.html>, chapter 6 (Environment Variables), including
OMP_NUM_THREADSandOMP_THREAD_LIMIT. - OpenBLAS runtime variables <http://www.openmathlib.org/OpenBLAS/docs/runtime_variables/>, the environment variables OpenBLAS reads at startup.
- Intel oneMKL reference: mkl_set_num_threads <https://www.intel.com/content/www/us/en/docs/onemkl/developer-reference-c/2023-0/mkl-set-num-threads.html>, the MKL threading-control calls.
- Linux manpage for fork() <https://man7.org/linux/man-pages/man2/fork.2.html>, behavior of threads after fork.
Where this appears
- threaded-r Must manage threads from BLAS, LAPACK, and user packages alongside R’s threading model.
- sunlight Fork does not reset the thread counts in external libraries, so sunlight starts its template with BLAS and OpenMP held to one thread and then gives each worker a share of the cores.