14.2 Shared Memory vs Message Passing

APPROACHESSTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-11-18
Before this page Shared Memory, Serialization

14.2.1 The choice

When multiple threads or interpreters need to exchange data, two strategies exist. Shared memory means both have pointers to the same object in the heap. Message passing means one sender prepares data, sends it through a queue, and the receiver deserializes into its own heap.

The first avoids copying, and the second avoids data races.

14.2.2 Overview

This choice determines the performance and complexity of data sharing. It also couples tightly with the isolation model: shared memory requires shared heaps, while message passing works with isolated heaps.

The choice affects API design, performance characteristics, and debugging difficulty. Shared mutable state is hard to reason about. Message passing introduces latency.

14.2.3 Option A: Shared Memory

Multiple threads read and write the same object. Both hold pointers to the same address. Access is immediate: no copy, no serialization.

This works only if access is coordinated. A mutex around the object protects mutations. Readers can proceed concurrently if the object is immutable. In a garbage-collected runtime, every store of a pointer into an object also runs the write barrier, which keeps the GC invariants, so the barrier’s own bookkeeping becomes shared state too.

Shared mutable state is complex. Compilers and CPUs both reorder loads and stores for performance, so a write on one thread is not guaranteed to become visible to another thread, in order, without synchronization. Atomics and locks provide that ordering.

Example: two threads increment the same counter. Each reads the old value, adds one, and writes it back. Without synchronization, both can read the same old value, and one increment is lost. An atomic increment, or a lock around the read and the write, keeps both.

In R, every object header holds a mark bit, a generation number and a reference count. The garbage collector writes the first two during collection, and the evaluator writes the reference count when a value is bound or stored. A SEXP shared between interpreters would need synchronization on every one of those writes, which makes naive sharing impractical.

14.2.4 Option B: Message Passing

Thread A prepares data, serializes it to a buffer, enqueues the buffer on a queue, and signals thread B. Thread B wakes, deserializes the buffer into its own heap, and owns the new copy.

No thread ever accesses memory another thread owns. The queue is the only synchronized object, and nothing else needs a lock.

Serialization and deserialization take time. A large matrix must be copied byte by byte, and a vector with ten million elements takes milliseconds to serialize. That is acceptable when the work on the other side takes much longer.

Example: at a copy rate of 10 GB/s, sending a 100 MB data frame takes 10 milliseconds. If the work takes 1 second, overhead is 1 percent. If the work takes 10 milliseconds, overhead is 50 percent.

Latency adds up. Suppose thread A sends a request and waits for thread B. The round trip costs serialization, queue transit, deserialization, the work itself, serialization again, and the return.

Throughput is high for batch work. If thread A sends one large task and waits for a result, amortized serialization cost is small. For a 1 GB matrix and a 10 second analysis, serialization at the copy rate above costs about 1 percent each way.

14.2.5 Scored on the nine dimensions

Dimension Shared Memory Message Passing
Isolation No isolation, requires synchronization Complete isolation, data is independent copy
Data movement Pointer access, no copy on read Copy required on send and receive
Startup cost Identical for both, not affected by this choice Identical for both, not affected by this choice
Steady-state overhead High: lock contention, atomic costs on every access Low: threads run freely without synchronization
Memory behavior One object, many references, save memory Each thread owns its copy, 2x or more memory
Portability All platforms support mutexes and atomics All platforms support queues and memcpy
Package compatibility Forces synchronization inside C packages Preserves single-threaded assumptions
Failure containment Corruption in shared state affects all threads Bad data spreads only through messages; a crash is contained only between processes
Determinism Memory ordering and reordering make it hard to reason about Deterministic if queue order is deterministic

14.2.6 Where each one wins

Shared memory wins on large mutable data, such as a model trained by all threads or a huge matrix modified in place. It also needs a codebase designed for threading, and it wins where latency is critical.

Shared memory is also the only choice for algorithms that require immediate visibility of updates. A collaborative filtering model updated in real-time by many workers needs shared state.

Message passing wins when data is mostly read, workloads are partitioned (map-reduce), or existing C packages must work unchanged. It is the default for isolated interpreters in separate processes.

Message passing is ideal for embarrassingly parallel problems: each worker processes independent data and returns results.

In practice, hybrids are common. Shared immutable data needs no synchronization. Mutable data uses message passing. Read-only matrices can be mapped into shared memory.

14.2.7 R today

GNU R is single-threaded. One thread owns all data. The question of shared memory versus message passing does not arise.

The parallel package implements message passing through process boundaries. With mclapply, the parent forks child processes, read-only data is shared through copy-on-write pages, and results are serialized back to the parent over pipes. With a socket cluster, both the work and the results are serialized over sockets.

Shared memory does exist within a single process: all variables in R live in the same heap. That follows from having one interpreter, not from a design choice about sharing.

sunlight uses copy-on-write sharing at the fork boundary. Workers inherit the template process’s heap, and the template and each worker share physical memory pages until one of them writes. The first write to a page gives the writer a private copy. Results are returned instead of mutated in place, but the worker’s garbage collector also writes, since marking sets a bit in the header of every live object it reaches.

14.2.8 Relevance to my work

threaded-r uses message passing for inter-interpreter communication. Each interpreter owns its heap, and data crossing a boundary is serialized onto a channel. No mutable SEXP is shared, so R-level data cannot race; on the data path the channel is the one synchronized object.

Message passing costs serialization time in proportion to the data sent. Where that cost starts to dominate for R workloads has not been measured; the copy arithmetic above gives its shape, not the answer.

Explicitly shared immutable data can reduce copying overhead. If a vector is marked immutable and registered in the immortal arena, both interpreters can read the same pointer. This requires enforcement at the type level and requires changes to the R object model.

r-in-rust keeps no global mutable state in its interpreter, so two of its interpreters can communicate only explicitly, through whatever the host program passes between them. That should make correctness easier to reason about.

Where this appears

  • threaded-r Uses message passing for data between isolated interpreters. Shares only immutable constants.
  • r-in-rust (rrs) Explores message passing as the only inter-interpreter communication mechanism.
  • sunlight A template process forks the workers, so they start out sharing its pages copy-on-write.

Where to go next

Back to top