7.3 The R C API and Thread Safety

ABI AND FFISTATUS: DEVELOPINGLEVEL: DEEPREVIEWED: 2026-11-15

7.3.1 Motivation

R’s C API was written for one interpreter running on one thread. Writing R Extensions states the thread half: its API functions “should only be called from the main thread of the R process”. The interpreter half is written down nowhere. Both assumptions are invisible in single-threaded code and become hard constraints in a threaded design.

7.3.2 The five architectural assumptions

The R C API assumes:

  1. One interpreter per process.
  2. One calling thread per interpreter.
  3. A process-global symbol table whose entries live forever.
  4. A process-global garbage collector with one heap.
  5. A process-global condition mechanism that uses longjmp().

A normal build enforces none of these. Only the second is documented, and only a checking build tests it: R configured with --enable-strict-barrier on a Unix-alike ends the process with “Wrong thread calling” when a thread other than the main one calls PROTECT or starts a collection. The rest are implicit. A C programmer writing against the API does not think about threads. The API does not require explicit synchronization. This is because the API assumes threading does not exist.

GNU R is a single-interpreter, single-process program. All C code runs on the main thread unless the programmer explicitly spawns workers. The C API makes no provisions for multiple interpreters or multiple calling threads.

7.3.3 Assumption 1: One interpreter per process

REALSXP is a constant in the header (#define REALSXP 14), so each package binary carries the number 14 compiled into it. That constant is no problem for a second interpreter: it was fixed at the package’s compile time, and every interpreter agrees on it.

What lives in the interpreter’s global state is different: the symbol table, the global and base environments, and the package search path. Those are process-global variables, and they are the ones a second interpreter collides with.

If two interpreters run in the same process, each must have its own copy of that state. But the C API does not pass an interpreter context. A C routine receiving a SEXP has no way to know which interpreter the object came from.

The result: a SEXP from interpreter A cannot safely be passed to C code running against interpreter B. The type tag is fine, since both agree that 14 means REALSXP. What is wrong is everything reached indirectly: the symbol table the routine consults, the protect stack it pushes onto, and the heap the collector will walk.

7.3.4 Assumption 2: One calling thread per interpreter

The protect stack is a process-global array, R_PPStack in GNU R. When C code calls PROTECT(x), it pushes onto this array. The index of the top is another global variable, R_PPStackTop.

Consider two threads calling into the same interpreter’s C code:

Thread 1 calls PROTECT(a), pushing to index 0. Thread 2 calls PROTECT(b), pushing to index 1. Thread 1 calls UNPROTECT(1), popping from index 1.

Thread 1 just unprotected b, not a. The state is corrupted.

This is a classic data race. Two threads access the same variable without synchronization.

The protect stack in GNU R is a mutable global array. If two threads call C code in the same interpreter, the protect stack is corrupted. PROTECT/UNPROTECT is not atomic. There is no lock.

Fixing this requires per-thread protect stacks, because existing C code counts on having the stack to itself. A C function that calculates UNPROTECT(5) from how many objects it protected is correct only if no other thread protected anything in between.

7.3.5 Assumption 3: Process-global symbol table

The symbol table maps each name to its one symbol object, a SYMSXP. install("x") returns the same SYMSXP every time it is given the same name, so C code and the evaluator can compare symbols by pointer.

Lookups take no lock. install() hashes the name into R_SymbolTable, a fixed array of chains, walks the chain, and on a miss allocates a new symbol and pushes it on the front of the chain. Two threads installing the same new name at once can both miss and both push, and then one name has two symbols. Symbols are never removed and the collector never moves them, which is what makes the pointer comparison safe in one interpreter.

If two interpreters have different symbol tables, C code that looks up a symbol in one interpreter cannot use the result in another. Packages often keep the result of install() in a C static variable, which then carries interpreter A’s symbol into interpreter B.

7.3.6 Assumption 4: Process-global garbage collector

Garbage collection runs when an allocation finds the heap past its current trigger size. The collector walks the root set: objects that are definitely in use. It marks all objects reachable from the roots. It sweeps unmarked objects.

In GNU R, the roots include:

  • Objects on the protect stack.
  • The global and base environments, and the symbol table.
  • The evaluation contexts of the R functions currently running, which hold their environments and arguments.
  • Objects kept alive with R_PreserveObject().

If two interpreters share the same heap, the garbage collector must know about both interpreters’ protect stacks, both environments, both call stacks. The collector must be told which objects belong to which interpreter. This requires explicit tracking.

The collector is also not concurrent. It runs on the thread that allocated and assumes nothing else touches the heap while it runs. If two interpreters on different threads share one heap, both must pause for a collection to be safe. This requires coordination.

Per-interpreter heaps can be garbage collected independently, and allocVector() does not need to change, because it never said which heap it uses. What breaks is a package that keeps a SEXP in a C static variable and later uses it from a different interpreter.

7.3.7 Assumption 5: Process-global error handling

R errors use longjmp(). When code calls error(), R finds the context that will catch the error and longjmps to it, unwinding the C stack back to that point.

R keeps its evaluation contexts in a process-global linked list headed by R_GlobalContext. A context that can be jumped to holds a jmp_buf filled by setjmp(), which records the stack pointer and return address of the thread that made it. error() walks the list from the top and longjmps to the first context that will take the error, whichever thread created it.

This is correct only if the handler’s thread is the one that called error(). If thread B calls error() and longjmps to a return address that was registered by thread A, the results are catastrophic. The stack pointer is wrong. Local variables are corrupted. Execution is undefined.

Error handling in GNU R uses a process-global list of error handlers. Multiple threads cannot safely call R functions or C functions that call back to R. A single error() call from one thread can longjmp into the stack of another thread.

7.3.8 Assumptions that rule out free threading

Free threading means that C code can run simultaneously on multiple threads, each calling into the same interpreter or different interpreters. The five assumptions above make this impossible:

  1. If C code from multiple interpreters runs in the same process, the C API does not pass context. C code cannot distinguish between objects from different interpreters.

  2. If multiple threads call into the same interpreter, the protect stack is corrupted.

  3. If multiple interpreters share a symbol table, the table must be locked. But the C API does not define a lock. Existing C code does not use one.

  4. If multiple interpreters share a heap, garbage collection must coordinate between them. The C API does not expose the coordination mechanism. Existing C code does not request it.

  5. If multiple threads call error(), the error handler list is corrupted. The longjmp is sent to the wrong thread.

Each assumption is independently a blocker. Together they make free threading incompatible with the C API.

7.3.9 Requirements for a thread-safe C API

A thread-safe API has to settle these five things:

  1. Tell each C function which interpreter the call is for, either with a context argument, which changes every function signature, or by keeping the current interpreter in thread-local storage.

  2. Make the protect stack per-thread or per-interpreter.

  3. Make the symbol table per-interpreter. Code that caches a symbol in a C static variable then needs a cache per interpreter.

  4. Give each interpreter its own heap and garbage collector. The API must define how objects can be passed between interpreters. This is expensive.

  5. Make error handling per-thread or per-interpreter, so that the list of contexts an error can jump to belongs to one thread.

Only the context argument in item 1 changes every signature. The rest can sit behind the existing API when the runtime finds the current interpreter through thread-local storage, which is the route threaded-r takes. None of them is free.

7.3.10 threaded-r and r-in-rust

The threaded-r project uses the apartment model: each interpreter has one owner thread. A C function called from interpreter A always runs on A’s owner thread. The five assumptions still hold within each apartment.

The C API does not pass interpreter context, so threaded-r keeps it in thread-local storage. The current thread’s state, protect stack included, lives there, and each interpreter has exactly one owner thread. When a C function calls PROTECT(), it pushes onto the stack of the thread it runs on, which is its interpreter’s stack.

This is not free. It requires:

  • Per-interpreter state, symbol table included. Two structures carry it: R_ThreadState for the state that belongs to a thread, and R_InterpreterState for the state that belongs to an interpreter.
  • Per-interpreter protect stacks.
  • Per-interpreter error handler lists.
  • Careful discipline: never allow a thread to switch interpreters without resetting thread-local state.

It preserves the C API at the source level. Existing packages compile against threaded-r unchanged, but they have to be compiled for it: threaded-r refuses a binary built for stock R.

The r-in-rust project takes a different approach. It builds the Rust interpreter with per-interpreter state by design and exports the C API over that state. When C code calls Rf_allocVector(), rrs allocates in the calling interpreter’s own heap and returns a handle that the package uses as an opaque SEXP.

This is also not free. Every accessor is a function call into Rust, and REAL(x) must still hand back a real double* into contiguous storage. But it lets rrs run native packages with an internal architecture that is completely different.

7.3.11 The hard lesson

The C API cannot be made safe for free threading without breaking existing code. Every solution requires either:

  • Rewriting C code to pass explicit context (breaks source compatibility).
  • Adding locks that existing code does not know about, while that code still assumes it has the interpreter to itself.
  • Accepting per-thread or per-interpreter costs (slows things down or increases complexity).

Further reading

  • Writing R Extensions <https://cran.r-project.org/doc/manuals/r-release/R-exts.html#OpenMP-support>, section 1.2.1.1 (OpenMP support), which calls the R API from threaded code “for experts only”.
  • Writing R Extensions <https://cran.r-project.org/doc/manuals/r-release/R-exts.html#The-R-API>, chapter 6 (The R API), which says its entry points should only be called from the main thread of the R process.
  • The Rustonomicon <https://doc.rust-lang.org/nomicon/send-and-sync.html>, the chapter on Send and Sync.

Where this appears

  • threaded-r The C API assumes a single interpreter and one calling thread per interpreter. Moving to multiple interpreters requires per-interpreter state.
  • r-in-rust (rrs) The compatibility layer must enforce that every boundary call has exclusive access to its interpreter, or the C API guarantees break.

Where to go next

Back to top