8.2 Shared Memory

CONCURRENCYSTATUS: STABLELEVEL: INTERMEDIATEREVIEWED: 2026-11-18

8.2.1 Motivation

Workers in the same process can read each other’s data directly. Workers in different processes cannot. Shared memory is the OS mechanism that maps the same physical memory into several processes, so they can read one copy of the data. For parallel R computing with large data, shared memory can remove serialization costs. It also moves the hard part from serialization to race conditions and mutual exclusion, and R objects are badly suited to it.

8.2.2 The problem

Consider two R workers computing on a 10 GB numeric vector. The copy-and-serialize path involves expensive work: serialize the vector to bytes, send bytes over a socket, deserialize into the worker’s heap. Repeat in reverse for results. With shared memory, both workers hold virtual addresses that point to the same physical RAM, and neither serialization nor copying happens.

But shared memory is only free when the data is simple. R objects embed mutable metadata even at rest. A SEXP header contains a reference count, which changes when references are added or dropped, and garbage collection bookkeeping, which the collector writes on every collection. Two processes sharing an R object would both write those fields, so they would have to coordinate even their reads, or risk silent corruption. Objects built from pointers (lists, environments, closures) add a second problem, covered below.

8.2.3 Mental model

Intuition

Shared memory is an OS abstraction. The kernel maps the same physical pages into the address spaces of several processes. Each process usually sees the data at a different virtual address, but all reads and writes go to the same physical location. This is how threads work by default: they all live in the same process and share the entire virtual address space. Processes, by contrast, start with separate address spaces. Sharing memory between processes requires explicit setup.

Processes gain instant access to large data with no serialization. In exchange, any mutable data needs synchronization, and pointers stored in the shared data lose their meaning across address spaces.

Mechanics

On POSIX systems (Linux, macOS, BSD), shared memory happens through two paired operations. First, one process creates a shared memory object using shm_open. The new object is named and has zero length (on Linux it is a file in the tmpfs mounted at /dev/shm), so the creator sizes it with ftruncate. Second, any process can open that object by name and map it into its address space using mmap. The OS manages translation from each process’s virtual addresses to shared physical pages.

On Windows, file mapping serves the same role. A process creates a file mapping object, usually backed by a file or pagefile. Other processes can open the mapping by name and use MapViewOfFile to get local virtual addresses. Internally, the Windows kernel maintains page tables for each process, making them all point to the same physical RAM.

Both approaches reach the same place: multiple page tables, one physical location. What follows from that is easy to get wrong. An address is meaningful only inside the process that holds it. Process A can see the data at 0x7f1234567890. Process B can see the same physical bytes at 0x5500abcd1234. Code running in Process A cannot store 0x7f1234567890 in shared memory and expect Process B to use it.

Runtime level detail

The kernel allocates the shared memory region and points the page table entries of every mapping process at the same physical pages. When Process A writes to a virtual address in its view, the CPU’s memory management unit translates it to a physical address. When Process B reads from its virtual address to the same physical location, the translation is different, but the destination is identical.

The CPU caches keep the copies consistent. Cache coherence protocols (MESI and variants such as MOESI) make every core agree on a single order of writes to each memory location, and a write by one core reaches the others’ view of that location. Coherence does not make writes to different locations appear in program order: store buffers and out-of-order execution can still reorder them, and the memory ordering described on the atomics page is what controls that. Processes that share pages get the same coherence, and the same reordering, as threads do.

Lifetime works differently from heap memory, which the OS reclaims when a process terminates. A POSIX shared memory object has kernel persistence: it exists until some process removes it with shm_unlink and the last mapping goes away, or until the system shuts down. A process that crashes before unlinking leaves the object behind. A Windows file mapping object, by contrast, closes once every view is unmapped and every handle is closed.

8.2.4 Mechanism: OS facilities

POSIX: shm_open and mmap

On Unix-like systems, the sequence is:

creator: shm_open("/name", O_CREAT | O_RDWR, 0644) -> fd
creator: ftruncate(fd, size)
creator: mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0) -> addr
consumer: shm_open("/name", O_RDWR, 0) -> fd
consumer: mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0) -> addr

The creator opens a named region, sizes it, and maps it. The consumer opens the same name and maps it. Both processes now have virtual pointers into the same physical pages. The OS maintains separate page tables for each process, but they translate to the same RAM.

Closing the descriptor and unmapping do not remove the object. Some process has to call shm_unlink("/name"), and if none does, the object stays until reboot. Cleanup is manual.

Windows: CreateFileMapping and MapViewOfFile

On Windows:

creator: CreateFileMapping(INVALID_HANDLE_VALUE, ..., size, "Global\\name")
creator: MapViewOfFile(...) -> addr
consumer: OpenFileMapping(..., "Global\\name")
consumer: MapViewOfFile(...) -> addr

With INVALID_HANDLE_VALUE in place of a file, the mapping is backed by the system paging file. The creator maps a region into its address space, and the consumer maps the same named object into its own. The object closes once every process has unmapped its views (UnmapViewOfFile) and closed its handles (CloseHandle).

The Global\ prefix puts the name in the global namespace, so processes in other sessions, such as a service and a logged-on user, can open it. Without a prefix, a process in a user session gets its own session’s namespace. Creating a file mapping in the global namespace from such a session needs the SeCreateGlobalPrivilege privilege (Kernel object namespaces <https://learn.microsoft.com/en-us/windows/win32/termserv/kernel-object-namespaces>).

8.2.5 A simple example

Imagine a server that precomputes numeric matrices and a pool of workers that perform calculations on them. With serialization, every job ships a copy of the matrix to the worker, even though the matrix is immutable and identical for all jobs.

With shared memory:

  1. The server creates a named shared memory region, loads the matrix data into it, and broadcasts the region name and dimensions to workers.

  2. Each worker uses the region name to map the matrix into its address space at a (possibly different) virtual address.

  3. Workers perform calculations on the local virtual pointer. Reads translate through the worker’s page table to the shared physical memory.

  4. Results come back to the server, but not the matrix.

The matrix is copied once, during setup. After that, a job carries only the region name and dimensions, and each worker reads the matrix through its own page tables.

This works because the matrix is flat numeric data, pointer-free, and read-only after setup. Nothing writes to it, so there is nothing to race on.

8.2.6 The hard part: R objects

A SEXPREC header embeds a reference count and garbage collection bookkeeping. The count changes when references are added or dropped, and the collector writes mark bits on every collection, including on objects the program only reads. Two processes that share an R object would both write those fields, so they must coordinate every access or corrupt the object’s metadata.

Beyond headers, R objects contain internal pointers. A list points to a SEXP in the creating process’s heap. That SEXP is stored in the list as a raw memory address. When another process maps the list, the pointer address is wrong. It points to the first process’s heap, which the second process cannot access.

R’s allocator also assumes it is alone. Its free lists and page pools have no locks, and nothing tells one process’s allocator what another has taken, so two processes allocating from the same heap pages would corrupt those lists.

Sharing R objects directly between processes would therefore need inter-process synchronization on every access to GC state, and every internal pointer turned into an offset resolved at access time.

8.2.7 Other systems

bigmemory R package

The bigmemory package sidesteps the R object problem. It does not share R objects. Instead, it shares flat, pointer-free numeric matrices.

A matrix is created with big.matrix(). By default the data is allocated in a named shared memory region. Workers receive a descriptor from describe(): the region name, dimensions, and data type. Each worker attaches the region with attach.big.matrix() and reads or writes the numeric buffer through the package’s own accessors, outside R’s heap.

This works because a numeric matrix is a contiguous byte sequence with no internal pointers and no mutable headers in the shared portion. The package allocates the metadata (dimensions, type, region name) in each process’s local heap. The expensive data lives in shared memory.

Apache Arrow

Apache Arrow defines a columnar memory layout designed for cross-language and cross-process sharing. A table is a sequence of columns. Each column is a sequence of byte buffers: data, validity bitmaps, offsets. Every element is identified by its position, not a pointer. The specification describes the format as relocatable without “pointer swizzling”, which is what allows zero-copy access in shared memory.

A server writes an Arrow table to shared memory or a file. Workers wrap the buffers in their own language’s objects, an Arrow Table in R or in pyarrow, and can convert that to a data frame or a pandas DataFrame. Neither the R nor the Python object is shared. Only the underlying columnar bytes are.

This approach avoids both the R object problem and serialization. The data is laid out once in a portable, pointer-free format. Workers reconstruct objects locally as needed.

8.2.8 Pipeline comparison

The traditional serialization pipeline is:

flowchart LR
  obj["R object<br/>in heap"] --> ser["serialize"] --> bytes["byte<br/>stream"]
  bytes --> sock["socket"] --> deser["deserialize"] --> obj2["full copy<br/>in worker heap"]

Serialization copies the object and converts structure to bytes.

The shared memory pipeline is:

flowchart LR
  data[("data in<br/>shared region")] --> handle["handle:<br/>name + offset + size"]
  handle --> sock["socket<br/>(tiny message)"] --> mmapstep["worker maps<br/>the region"]
  mmapstep --> view["worker reads<br/>same pages"]
  view -.->|no copy| data

Shared memory sends a handle, then maps the existing data.

Serialization is expensive for large objects but simple for any object type. Shared memory is cheap per byte but works only for data with no mutable metadata and no internal pointers.

process A region mapped at 0x7f12… plus a private heap process B region mapped at 0x5500… plus a private heap the same physical pages mmap mmap no serialization, but a pointer into one private heap means nothing in the other process

Two process address spaces map different virtual addresses to the same physical shared region.

Process A sees the shared region at virtual address 0x7f12… Process B sees it at 0x5500… Both page tables map their respective virtual addresses to the same physical pages. If Process A writes to 0x7f12…, Process B reads from 0x5500… and sees the updated value. Concurrent writes to the region still need synchronization, exactly as they would between threads.

8.2.9 The hard part: pointers and relocation

Shared memory requires that stored references be portable across address spaces. A raw pointer will not work. Process A stores the address 0x7f12… expecting Process B to use it. Process B gets a different mapping and cannot follow the pointer.

Two solutions exist. First, relocatable references use offsets or handles instead of raw addresses. A reference holds an offset from the start of the region. Resolving the reference requires adding the base to the offset, or looking up the handle in a directory. Apache Arrow uses this approach: elements are identified by column and row index, not pointer address.

Second, addresses can be coordinated. If the OS maps the shared region to the same virtual address in every process, raw pointers into the region stay valid everywhere. This requires every process to keep that address range free, and it weakens address space layout randomization (ASLR).

8.2.10 Obstacles to mapping R objects

An R object’s header (its SEXPREC) embeds mutable garbage collection state. Reference counts change as references come and go, and mark bits change on every collection. A shared SEXP requires inter-process synchronization for nearly every operation.

R objects contain internal pointers to the heap. These pointers are meaningless in other address spaces and cannot be relocated automatically.

R’s allocator has no locks. Multiple processes allocating from the same heap concurrently corrupt the freelists and metadata.

These three constraints make direct sharing of R objects between processes impractical. Serialization, despite its cost, is simpler than coordinating mutable heap state across process boundaries.

Immutable flat vectors are the most plausible first candidate for cross-interpreter sharing. A vector with no pointers to the heap, fixed layout, and no mutable metadata can be shared without synchronization. The shared immutable vectors design question explores this idea.

8.2.11 Relevance to my work

The sunlight package forks worker processes and relies on copy-on-write to save memory. When a child process writes, the kernel copies the affected page, breaking the shared mapping. A full garbage collection in a child privatizes most of the inherited pages anyway: one gc() in a plain R child privatized about 79 percent of the parent’s heap. sunlight does not use explicit shared memory.

For threaded-r, shared memory is not the blocking issue. Threads already share all memory by default. The challenge is coordinating R’s mutable heap across threads, which requires different mechanisms than cross-process shared memory.

Shared memory comes back for any design that moves data between processes: if threaded-r computes in one thread and must pass results to another process, it needs serialization or shared memory.

8.2.12 Open questions

How can R data structures be redesigned for shared memory? One approach: separate immutable columnar layouts from the R object system, like Arrow does. Another: per-interpreter heaps that several processes can map, with references resolved through a table of region base addresses. Neither has been tried in my work.

Can reference counting work across processes? Global reference counts require atomic updates and cross-process coordination. Thread-local reference counts do not scale to process boundaries.

Further reading

  • POSIX: shm_overview(7) <https://man7.org/linux/man-pages/man7/shm_overview.7.html>, shm_open(3) <https://man7.org/linux/man-pages/man3/shm_open.3.html> and mmap(2) <https://man7.org/linux/man-pages/man2/mmap.2.html> in the Linux man-pages project document the calls and the object lifetime.
  • Windows: File Mapping documentation <https://learn.microsoft.com/en-us/windows/win32/memory/file-mapping> in the Windows API reference.
  • Virtual memory: chapters 13 to 23 of Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces <https://pages.cs.wisc.edu/~remzi/OSTEP/>, cover address spaces, paging and TLBs.
  • Apache Arrow: Arrow memory layout documentation <https://arrow.apache.org/docs/format/Columnar.html> describes the columnar format designed for cross-language sharing.
  • R internals: the SEXPs <https://cran.r-project.org/doc/manuals/r-release/R-ints.html#SEXPs> and Memory allocators <https://cran.r-project.org/doc/manuals/r-release/R-ints.html#Memory-allocators> sections of “R Internals” (R Core Team) describe the object header and the allocator.

Where this appears

Where to go next

Back to top