flowchart TB
subgraph psock["PSOCK path"]
direction LR
a(["R object"]) --> s["serialize()"] --> k["socket"] --> u["unserialize()"] --> b(["full copy in<br/>worker heap"])
end
subgraph forkpath["FORK path"]
direction LR
c(["R object"]) --> pt["fork marks pages<br/>read-only"] --> d(["child sees the<br/>same pages"])
pt --> w["a write copies<br/>only that page"]
end
psock ~~~ forkpath
8.1 Processes vs Threads
8.1.1 Motivation
Every parallel R design starts by deciding whether a worker is a process or a thread. That choice fixes three costs at once: worker startup, data movement, and failure containment. On the first two, the options differ by orders of magnitude. R today offers only processes.
8.1.2 The problem
The standard parallel backends in R all run each worker as a separate process. The isolation between processes is what keeps them safe, and copies are its price: each spawned worker holds its own copy of the runtime, of the loaded packages, and of any data it receives. Thirty-two spawned workers sent the same gigabyte data frame hold thirty-two copies of it. Threads share one copy of everything, so the same job is one runtime, one data frame, and thirty-two concurrent readers.
8.1.3 Mental model
An address space is the full range of memory addresses a program can use. The kernel maps those addresses to physical RAM through page tables. Two processes can use the same numeric address and reach different physical bytes. That mapping is the isolation: a pointer from one process means nothing inside another, so processes cannot exchange data through raw pointers.
A process is the unit of isolation. It owns an address space, file descriptors, and at least one thread. A thread is the unit of execution. The kernel scheduler places threads on CPU cores. All threads inside one process share the full address space. Each thread owns only its stack, its CPU registers, and its thread-local storage.
Each process has its own heap, so R workers exchange data as serialized copies. Threads share one heap and add only a private stack each.
8.1.4 Mechanism
Process structure and isolation
A process owns three things at the kernel level. First, the address space. The kernel creates page tables that map virtual addresses to physical RAM. A pointer has meaning only within that single mapping. Second, the file descriptor table: open files, sockets, and pipes. These resources belong to this process alone. Third, the process owns signal handlers, environment variables, and the working directory. When the process exits, the kernel frees its memory and closes its descriptors.
A crashed worker process therefore cannot corrupt its siblings. The kernel enforces that containment on every memory access, so the program does nothing to get it.
Thread structure and sharing
A thread owns three things of its own. First, its stack: the memory region holding local variables and call frames. Second, its register state, including the program counter, which holds the address of the next instruction. Third, its thread-local storage: variables where each thread sees a private copy. Everything else threads share: the heap, global variables, loaded code, file descriptor table, and signal handlers.
Thread A allocates a ten gigabyte matrix on the heap. Thread B reads it through a pointer. No copy occurs and no bytes move across any channel. That sharing is the whole performance argument for threads, and it is also the safety problem described below.
Process creation
Unix systems create processes in two ways. The first is fork(). Fork duplicates the calling process: the same code, the same file descriptors, and logically the same memory. The child continues from the same instruction. If the parent has several threads, the child gets a copy of only the thread that called fork(), and POSIX <https://pubs.opengroup.org/onlinepubs/9799919799/functions/fork.html> allows the child only async-signal-safe calls until it runs exec. A lock that another parent thread held at the moment of the fork stays locked in the child, with no thread left to release it. Modern kernels use copy-on-write to make fork fast; the internal mechanics below cover it. The second way is spawn: start a fresh program from an executable file. A spawned R worker starts empty. It must load R itself, then load every required package from disk.
The Windows API has no fork. Its process creation call, CreateProcess, always starts a fresh program. This is why parallel::mclapply, which uses fork, runs in parallel on Linux and macOS but only serially on Windows, where asking it for more than one core is an error. A portable R parallel design cannot rely on fork.
Thread creation skips most of this work. The thread library maps a stack, and the kernel adds one task to the scheduler. The NPTL developers <https://www.akkadia.org/drepper/nptl-design.pdf> reported starting and stopping 100,000 threads in 2 seconds on early-2000s hardware, about 20 microseconds per thread. Fork has to copy the parent’s page tables and mark its pages read-only, so its cost grows with the size of the parent. Baumann and colleagues <https://doi.org/10.1145/3317550.3321435> measured fork plus exec at under a millisecond for a small parent and at 7 to 24 milliseconds for a 256 MiB one. A spawned R worker with a heavy package stack takes seconds.
Context switching
A context switch occurs when the scheduler stops one task and resumes another. The kernel saves registers from the first task and restores registers from the second. Between two threads of the same process, that is nearly all the work. Between two processes, the kernel must also switch page tables. Unless the CPU tags its TLB entries by address space (PCIDs on x86, ASIDs on Arm), that switch empties the TLB, a small cache of recent address translations, and the new process refills it through slow page table walks. Either way, the new task starts with caches full of the old one’s data. Li, Ding and Shen <https://www.usenix.org/legacy/events/expcs07/papers/2-li.pdf> measured the direct cost of a switch between two processes at 3.8 microseconds on a 2007 Xeon, and the total cost, cache refill included, at anywhere from several microseconds to over a millisecond, depending on how much data the processes touched.
Memory footprint
An idle R process occupies tens of megabytes: a bare Rscript session of R 4.6.1 on Windows has a working set of about 60 MB. Add a heavy package stack, and one session consumes hundreds of megabytes to gigabytes. Multiply by worker count. Thirty-two spawned workers holding the same packages means thirty-two copies of the same package code and data. Threads change this equation. Each extra thread costs one stack, whose default size on Linux follows the stack size limit, commonly 8 MB (pthread_create(3) <https://man7.org/linux/man-pages/man3/pthread_create.3.html>). Most of that is reserved address space, not memory in use. The packages, code, and data exist once, visible to all threads.
Data communication
Processes cannot share pointers, so they communicate through the kernel: pipes, sockets, or explicit shared memory regions. Structured objects cannot pass through a pipe or socket as bytes. They must first flatten into a byte stream: serialization. Serialization costs CPU time on both ends, doubles memory while both copies exist, and adds latency per message.
Threads communicate by passing a pointer. The transfer is free. The new cost is coordination. If two threads write the same address without coordination, the result is a data race, and in C or C++ the program’s behavior becomes undefined. Fixing this requires a mutex, atomics, or a design that never shares mutable state. Synchronization has real cost. For large data, it remains far below serialization cost.
8.1.5 A simple example
The costs above appear in ordinary R code. Build a large numeric matrix and send a trivial task to a PSOCK cluster.
x <- matrix(rnorm(5e7), ncol = 100) # about 400 MB of doubles
cl <- parallel::makeCluster(4) # 4 freshly spawned R processes
parallel::clusterExport(cl, "x") # serialize x, 4 times, over sockets
res <- parallel::parLapply(cl, 1:4, function(i) sum(x[, i]))
parallel::stopCluster(cl)The makeCluster call spawns four empty R processes and waits for each to start up. The clusterExport call serializes all 400 megabytes once per worker. After it returns, the machine holds five copies of x: two gigabytes for a task that reads four columns. On my Windows machine the export took about 3 seconds, and each worker then computed for about 3 milliseconds.
Now imagine the thread version that R cannot express. Four threads receive the task, index into the one existing x through a pointer, and return four numbers. Total data moved: four columns read in place, four numbers returned. Nothing serializes and nothing copies.
8.1.6 Internal mechanics
Fork and the kernel clone interface
On Linux, process creation and thread creation use the same kernel operation. fork(2) and pthread_create both end in the clone system call (clone or clone3, both documented in clone(2)). The flags passed to it declare what parent and child share. Fork passes no sharing flags: the child gets copies of page tables and creates its own copies on write. Thread creation passes CLONE_VM and CLONE_FILES among others: the child shares the address space and file descriptors. To the kernel, both results are tasks in the scheduler. “Process” and “thread” name two ends of one sharing spectrum. The apartment model described later aims at a middle point: thread-level sharing of one address space with isolation rebuilt inside the runtime.
Copy-on-write mechanics
Fork does not copy memory up front. The kernel copies only the page tables, so parent and child map the same physical pages initially. It marks those pages read-only in both. When either side writes to a page, the CPU raises a page fault. The kernel handles the fault by copying that one page, typically four kilobytes, remapping the writer to the private copy, and resuming the write. Pages that neither side writes stay shared. A forked R worker that only reads a large data frame shares those pages physically with the parent.
The trigger for copying is any write to the page, not only a write the user’s code performs. Bookkeeping writes by the runtime count too. Garbage collection walks every reachable object and writes mark bits into headers, so it privatizes many shared pages. The sunlight measurement under “R’s approach” shows how much fork saves in practice.
8.1.7 Tradeoffs
| Dimension | Processes | Threads |
|---|---|---|
| Startup | fork: under a millisecond to tens of milliseconds, by parent size; spawn plus packages: seconds | tens of microseconds |
| Data in | serialization or copy-on-write pages | pointer, zero copy |
| Data out | serialization back to parent | pointer, zero copy |
| Memory | one runtime image per worker | one runtime image total |
| Crash isolation | kernel enforced, one worker dies alone | one thread crash kills all |
| Safety | isolation by page tables | coordination by programmer |
The last two rows explain why processes remain popular despite their costs. A segfault in one worker process costs the tasks that worker held, and the other workers survive. A segfault in one thread kills every worker and the parent, because they are one process. The kernel enforces process isolation on every access. Runtime synchronization requires discipline from every line that touches shared state.
8.1.8 R’s approach
R parallelism today is process based. One process holds one interpreter, and every mainstream backend starts more processes.
parallel FORK clusters and mclapply fork the running session. Children inherit the parent’s memory through copy-on-write. Results return serialized, over a pipe for mclapply and over a socket for FORK clusters. Unix only.
parallel PSOCK clusters spawn fresh Rscript processes. Inputs and results travel as serialized bytes over local sockets. This is the only parallel cluster type on Windows.
future is an API layer over these transports. multicore uses fork, multisession uses PSOCK.
callr spawns a fresh R process per call. It serializes the function and arguments to a file, and the child serializes its result to a file.
mirai keeps persistent daemon processes. Tasks and results travel as serialized messages over NNG sockets or pipes.
The plumbing differs, but every backend pays serialization or copy-on-write, and every backend pays process startup.
PSOCK moves every object through serialize and unserialize. Fork moves nothing until a write privatizes a page.
Threads do run inside R today, but never as interpreters. A multithreaded BLAS parallelizes one matrix multiply across cores. data.table runs OpenMP threads inside its C routines. These cases stay safe because the threads live entirely below the R API. They start inside one C call, touch only raw arrays, and join before the call returns. The interpreter never sees them. What R lacks is threads at the R level: two threads that each evaluate R code.
The fork path looks nearly free, and measurement says otherwise.
sunlight measured how much memory forked R workers keep shared. A full garbage collection in the child walks every reachable object and writes mark bits into each object header. Those writes trigger page faults on nearly every shared page, and copy-on-write privatizes them. In the Day 7 run of 2026-08-01, the summed PSS of sunlight’s workers was only 1.28x below the summed RSS of the best incumbent at 8 workers and 1.10x below at 32, against a 5x goal. PSS splits each shared page among the processes that map it, while RSS counts it in full, so the comparison itself favors sunlight. The run was on WSL2, and it leaves out crew, which did not start all its workers. See fork, copy-on-write, and the first GC.
Since fork does not deliver cheap memory, sunlight attacks the other process cost: startup. sunlight keeps a prewarmed template process. The template loads R and the packages once. Each worker forks from the template and starts with everything already in memory. In the project’s own benchmark, standing up new workers from a live template was 3.3 to 5.9 times faster than the best incumbent. Cold start to a first result with Seurat loaded and 32 workers took 4.8 seconds against 14.9 seconds, but that run favored sunlight: all frameworks ran in one process in a fixed order, sunlight last against a warm file cache, under WSL2.
8.1.9 The hard part
For R workloads that share large objects, threads remove both process costs at once. A thread pool starts once, then hands out tasks in microseconds each. Workers read the input data in place, with zero serialization in and zero out. One runtime image serves any worker count, so memory stays flat as parallelism grows. The JVM, Go and Rust run threads in parallel over one shared heap, and CPython’s free-threaded build (PEP 703) now does too. The reasons R cannot do the same today have a page of their own: why R is difficult to parallelize.
GNU R assumes it is alone in the process. A census during threaded-r development found 1,574 mutable globals in the upstream sources. The evaluator, the symbol table, and the garbage collector all write shared state on almost every operation, so two threads running R code in one interpreter would corrupt it. The assumption extends past R itself. On 2026-10-21, 5,569 of the 25,474 packages on CRAN declared NeedsCompilation: yes, and their native code calls an R API that Writing R Extensions <https://cran.r-project.org/doc/manuals/r-release/R-exts.html#OpenMP-support> calls “for experts only” from threaded code.
In GNU R, an object the program only reads still gets written. GC bookkeeping lives inside every SEXP header, and the collector mutates it while it scans.
8.1.10 Relevance to my work
threaded-r takes the middle path on the clone spectrum: the apartment model. One process holds several complete interpreters. Each interpreter is owned by exactly one thread, and no thread touches another apartment’s state. Isolation moves from the kernel’s page tables into the runtime’s discipline. The multi-interpreter architecture page develops the design.
In threaded-r today, all 35 per-thread globals live in R_ThreadState, and R_InterpreterState had 556 members after patch 0127 (2026-08-22). Each interpreter owns its generational heap rings and collects them without touching another’s. Builtin constants such as R_NilValue live in one immortal arena that all interpreters share, so the separation is real but not total.
With per-interpreter heaps, an apartment process can hand an immutable object to another apartment as a pointer. That transfer costs what a thread transfer costs, near zero, while each interpreter keeps process-style isolation from the others. The apartment model then beats processes on all three costs: startup, data movement, and memory.
r-in-rust demonstrates the same shape from a clean slate. Each interpreter instance owns its heap, its garbage collector, its symbol table, and its string cache. The project permits no global mutable state in the interpreter, and a gate check enforces the rule. Many interpreters therefore coexist in one process by construction, not by patching. sunlight takes the pragmatic track. It accepts today’s process-based world and removes the largest cost it can reach, startup, without any change to R itself.
Further reading
parallelpackage vignette, R Core Team. In R:vignette("parallel", package = "parallel"). Online: https://stat.ethz.ch/R-manual/R-devel/library/parallel/doc/parallel.pdffork(2)andclone(2), Linux man-pages project: https://man7.org/linux/man-pages/man2/fork.2.html and https://man7.org/linux/man-pages/man2/clone.2.html- Arpaci-Dusseau and Arpaci-Dusseau, Operating Systems: Three Easy Pieces. Free online: https://pages.cs.wisc.edu/~remzi/OSTEP/. See the chapters “Processes”, “Process API”, and “Concurrency and Threads”.
Where this appears
- threaded-r Puts several isolated interpreters on separate threads inside one process.
- r-in-rust (rrs) Builds each interpreter with zero global state, so many fit in one process.
- sunlight Attacks the startup cost of process-based workers with a prewarmed fork template.