flowchart LR
A["Thread A"]
B["Thread B"]
I1["Interpreter 1<br/>owned by A"]
I2["Interpreter 2<br/>owned by B"]
A -->|can evaluate| I1
B -.->|cannot evaluate| I1
B -->|can evaluate| I2
A -.->|cannot evaluate| I2
13.3 Interpreter Lifecycle and Thread Affinity
An interpreter has a lifetime: creation, execution, destruction. The key constraint is thread affinity. One thread owns each interpreter and is the only one that can touch its state. Break this rule and you get races, corruption, or deadlocks.
13.3.1 Creation
An interpreter is born when a thread calls a creation function. In threaded-r, this is R_NewInterpreter(). In r-in-rust, it is Interp::new().
Creation allocates the interpreter struct, initializes the heap, builds the base environment, and returns an opaque handle. In threaded-r the handle is an R_ThreadState *, and the new interpreter is current on the calling thread when the call returns.
R_ThreadState *st = R_NewInterpreter();
/* thread A now owns this interpreter; NULL means no interpreter in
the process has finished the process-wide bootstrap yet */The thread that calls the creation function becomes the owner. Ownership is exclusive. Thread A owns this interpreter. Thread B cannot touch it. Only thread A can call functions on this interpreter.
Each threaded-r interpreter is owned by exactly one thread, fixed at creation. Ownership cannot transfer to another thread. In r-in-rust the interpreter value can be moved to another thread whole, but only one thread holds it at a time.
Creation is not free. The interpreter allocates fresh structures:
- A new heap
- A new symbol table with builtins
- A fresh base environment
- A new RNG seed
- A record of the connections it owns (threaded-r still shares one process-wide connection table)
- An empty options list
In r-in-rust, Interp::new() builds the heap, symbol table, string cache and RNG as fields of one Rust value.
In threaded-r, creation can reuse the shared immortal arena for builtin constants, saving allocation overhead.
13.3.2 Initialization
After creation, the interpreter is bare. A plain R_NewInterpreter() does not even attach base, so it can run only C-level evaluation, and no packages are loaded.
Initialization loads packages. library(stats) in R is an initialization step from the interpreter’s perspective. The package’s namespace is read from its installed lazy-load database, its compiled code is loaded with dyn.load, and the package is attached to this interpreter’s search path.
threaded-r cannot share a loaded package between interpreters, because a namespace is made of SEXPs and no SEXP crosses. Each interpreter bootstraps itself and loads its own packages. sunlight takes the other route with processes: it starts a template R process, loads a declared set of packages once, and forks workers that inherit them.
Initialization must happen on the owner thread. Thread A cannot initialize thread B’s interpreter. This rule prevents race conditions.
In practice, initialization often happens right after creation. R_NewInterpreterEx(R_INTERP_BOOTSTRAP_BASE) attaches base and the fork’s worker package set in the same call, and the owner can then load more:
R_ThreadState *st = R_NewInterpreterEx(R_INTERP_BOOTSTRAP_BASE);
ParseStatus status;
SEXP code = PROTECT(R_ParseVector(mkString("library(stats)"), -1,
&status, R_NilValue));
int err = 0;
if (status == PARSE_OK)
R_tryEval(VECTOR_ELT(code, 0), R_GlobalEnv, &err);
UNPROTECT(1);13.3.3 Execution
The owner thread executes code in the interpreter with the ordinary C API, as above: R_tryEval on this interpreter’s R_GlobalEnv, which is the global environment of whichever interpreter is current on the calling thread.
Only thread A can evaluate code in this interpreter. Thread B cannot.
Evaluating R code modifies the interpreter’s state. It allocates SEXPs in the heap, interns symbols, and can change options. None of these writes takes a lock, so only one thread may evaluate in an interpreter at a time. threaded-r generalizes R’s own thread check, R_check_thread, from one process-wide main thread to each interpreter’s owner. Like the original, it is a debug-build assertion (THREADCHECK), not a check that release builds make.
Each thread owns its interpreter. No thread can execute code in another’s interpreter.
Switching interpreters
In threaded-r, a thread owns one interpreter for that interpreter’s whole life. The fork has no call that switches a thread to a different interpreter or hands an interpreter to another thread. An attach and detach design, which would move ownership between threads, exists on paper in the threaded-r repository and is left out of the public header on purpose: a declared function with no implementation would be a worse promise to an embedder than no function.
The current-interpreter pointer lives in thread-local storage, so finding “this thread’s interpreter” needs no global synchronization.
13.3.4 Interruption
An interrupt signal (Ctrl+C) sets an interrupt flag. The evaluator polls it during evaluation (GNU R checks about every thousand calls to eval), and when it sees the flag set it stops and signals an R interrupt condition.
In GNU R, Ctrl+C sets the process-wide flag R_interrupts_pending. threaded-r keeps that flag process-wide, because SIGINT itself is process-wide, and lets only the main interpreter consume it, so Ctrl+C interrupts the interactive session and never a background worker. A worker is stopped instead through a cancel request, an atomic member of that worker’s own interpreter state.
Interruption is the one place where another thread must reach into an interpreter, so the flag it sets has to be atomic. A plain int written by thread B and read by interpreter-1’s evaluator on thread A is a data race.
13.3.5 Termination and cleanup
When an interpreter is no longer needed, it is destroyed. The owner thread calls a destroy function.
R_DestroyInterpreter(st);Destruction must run on the owner thread. The interpreter’s state (heap, symbol table, options) all live in structures tied to this thread. Only this thread can safely free them.
Before destruction, the owner must make sure no other thread references this interpreter. If thread B holds a SEXP from interpreter-1, and interpreter-1 is destroyed, thread B has a dangling pointer.
An interpreter can be destroyed only when no other thread holds references to its objects.
The apartment model forbids shared objects, so thread B never holds a SEXP from interpreter-1, and destruction is safe.
In a design that allows shared objects, such as shared immutable vectors, destruction must wait until all references disappear. That waiting is part of why the apartment model starts without shared objects.
In threaded-r, R_DestroyInterpreter works in this order:
- Run remaining finalizers while the interpreter is still fully valid
- Release the symbol table and string cache
- Free the heap and its garbage collector state
- Free the interpreter and thread state structs, and the thread’s signal stack
13.3.6 One thread per interpreter
Single-threaded interior means no locks on the interpreter loop. Thread A evaluates code in interpreter-1 without acquiring a lock, and reads and writes interpreter-1’s state freely.
If multiple threads could execute in the same interpreter, every access to shared interpreter state would need a lock or an atomic operation.
The apartment model chooses isolation over sharing. Each interpreter is single-threaded (has one owner). Interpreters communicate through messages and copying. This is slower than shared memory but eliminates synchronization overhead on the common path (running R code).
13.3.7 Forbidden operations
One thread per interpreter forbids some patterns:
Shared objects. Thread B cannot hold a SEXP from interpreter-1. The reference becomes invalid if interpreter-1 is destroyed.
Concurrent access to the symbol table. Two threads cannot both define functions in the same interpreter. The symbol table is not thread-safe.
Cooperative multitasking. Threads cannot yield to each other within the same interpreter. Only coroutines in a single-threaded environment can do that.
Lightweight futures. Spawning a task in the same interpreter from a callback requires a second thread. The callback runs in thread-1. It cannot spawn work in thread-1’s interpreter (this creates concurrent access). It must spawn in a different interpreter owned by thread-2.
13.3.8 Other systems
CPython does not bind an interpreter to one thread. Any number of OS threads can run in one subinterpreter, each with its own thread state, taking turns under that interpreter’s GIL. The isolation is between interpreters, not between threads.
A Lua state has no owner thread, but it is not thread-safe, so the embedder must keep each state on one OS thread at a time. That is a weaker rule than threaded-r’s, which ties an interpreter to the thread that created it.
A V8 isolate “can be entered by at most one thread at any given time”, and v8::Locker lets threads take turns with one isolate. Node.js gives each worker thread its own heap and passes messages between them.
A Ruby Ractor holds one or more threads, which take turns under that Ractor’s lock; threads in different Ractors run in parallel. Ownership runs the other way from threaded-r: the Ractor owns its threads.
One thread per interpreter is simpler and faster than the locking that concurrent execution within one interpreter would need. The cost is that multithreading work must happen across interpreters, not within one.
13.3.9 Next: State lifecycle
Each piece of per-interpreter state has its own lifetime. Global environments outlive connections. Heaps outlive individual SEXPs. What State Belongs to an Interpreter, the page before this one, catalogs that state.
Further reading
- threaded-r, my fork of GNU R, which creates and destroys interpreters this way. Its repository is not public yet.
- PEP 734, “Multiple Interpreters in the Stdlib” <https://peps.python.org/pep-0734/>, Eric Snow. Final in Python 3.14; supersedes PEP 554. Describes how threads relate to interpreters in
concurrent.interpreters. - Programming in Lua, first edition, chapter 9, “Coroutines” <https://www.lua.org/pil/9.html>, Roberto Ierusalimschy. What a Lua “thread” is.
v8::Isolateclass reference <https://v8.github.io/api/head/classv8_1_1Isolate.html>, V8 API documentation, including the rule that one thread at a time may enter an isolate.
Where this appears
- threaded-r The core constraint: one owner thread per interpreter enables fast execution without synchronization on the interpreter’s state.
- r-in-rust (rrs) Each interpreter is one Rust value owned by one thread at a time; the type is Send and not Sync, so the compiler keeps a second thread out.