flowchart TD
A["Concurrent access,<br/>one of them a write?"]
A -->|No| B["No race"]
A -->|Yes| C{"Synchronized?"}
C -->|Yes| D["No data race"]
D --> E["Does the result<br/>depend on timing?"]
E -->|Yes| F["Race condition only"]
E -->|No| G["Correct"]
C -->|No| H["Data race<br/>Undefined behavior"]
H -->|timing also<br/>breaks the logic| I["Both data race<br/>and race condition"]
8.3 Race Conditions
8.3.1 Motivation
A race condition is a flaw in concurrent program logic. The program’s correctness depends on the relative timing of threads. When threads access shared memory, the order in which their steps interleave can decide the result. Some orderings produce correct results. Others do not.
8.3.2 The problem
Two terms get confused: race condition and data race.
A data race is unsynchronized concurrent access to one memory location. At least one access must write. In C and C++, data races cause undefined behavior: the language makes no promise about what the program does.
A race condition is a logic error at a higher level. Race conditions can exist without data races. A thread can check that a file exists. A second thread can delete it. The first thread then tries to open it. No data race occurred, and the program still raced.
8.3.3 Mental model: intuition
The canonical example is the lost update. Two threads increment a shared counter. Each executes the same R code: count <- count + 1. This single line hides multiple steps.
An increment is three steps: load the value, add one, store it back. Read, modify, write. CPUs do have atomic increment instructions, but ordinary code does not use them, so another thread can run between the steps.
If thread A reads 0, and thread B reads 0 before either writes back, one increment vanishes. Both threads add 1 to the value 0. Both write 1 back. The counter is 1, not 2.
Thread B reads the counter after A’s read but before A’s write, so both threads write 1 and one increment is lost.
8.3.4 Mental model: how it works
Synchronization prevents this. A mutex is a lock that allows one thread to access a resource at a time. When thread A holds the mutex, thread B must wait. Only after thread A releases the mutex can thread B proceed. The read-modify-write becomes atomic from the program’s perspective.
An atomic is a special variable type that guarantees atomic operations on its value. The CPU performs the read, modify, and write as one indivisible operation: a single instruction on x86 and on recent Arm cores, or on older Arm cores a short loop that retries until no other core has written in between. Thread A increments the atomic. Thread B increments the atomic. The counter is now 2.
A lock-free atomic operation never puts a thread to sleep, while a contended mutex can, which costs a context switch. Atomics are usually faster for a counter or a flag, though under contention they still wait for the cache line. Not all operations can be expressed atomically, and when the logic spans several values, a mutex is necessary.
# Without synchronization: race condition
count <- count + 1
# With a mutex: serialized
lock$acquire()
count <- count + 1
lock$release()
# With an atomic: hardware-assisted
atomic_increment(count)8.3.5 Mental model: the three cases
Not all concurrent access is a race. There are three cases:
No race. One thread reads, another reads. Both see the same value. No synchronization is needed.
Race condition, no data race. The file example above: the program logic raced, but no memory location was written by one thread and read by another without synchronization.
Data race. Two threads access the same memory location without synchronization, and at least one of them writes. The language makes no guarantee about the outcome. This is undefined behavior in C and C++.
Race condition vs data race. A data race is a memory-level property. A race condition is a logic property.
8.3.6 Races in single-threaded R
GNU R executes one interpreter per process. All R code in that process runs in a single thread of evaluation. Only that thread modifies R objects. No two threads compete for the same R data structure.
Because the R interpreter is single-threaded, R code cannot have a data race on an R object. Race conditions are still possible between processes: two parallel workers writing the same file is one. Packages can spawn system threads for I/O or parallelization, but those threads must not call the R API; they hand their results back to the main thread. The R interpreter remains the sole modifier of R data.
This changes when a single process runs multiple interpreters. Two interpreters in the same process can execute R code concurrently, and data races on R’s own state become possible.
8.3.7 Where races appear in threaded R
The census of GNU R found 1,574 mutable globals. threaded-r moves some of them into per-interpreter state and protects others, because they are process-wide. The cases below show what goes wrong when two threads touch the same R state without that work.
Environment bindings. Two threads can write to the same environment simultaneously. If one thread defines a new variable while a second looks one up, and the definition makes R grow the environment’s hash table, the reader can walk a table that is being rebuilt. Concurrent access to environment internals can corrupt data structures.
Promise forcing. A promise is an unevaluated expression attached to a function argument. When a thread forces a promise for the first time, it evaluates the expression and stores the result. If a second thread forces the same promise concurrently, it usually finds the promise marked as under evaluation and gets the recursion error. If both threads pass that check before either sets the mark, the expression runs twice, side effects included, and the two writes to the value slot race.
Reference counting. Every R object carries a reference count in its header. When a thread creates a reference, it increments the count. When a thread drops a reference, it decrements the count. If two threads modify the count without synchronization, the count becomes incorrect. R uses the count to decide whether it may modify an object in place, so a count that is too low lets R change an object that something else still refers to. The garbage collector, not the count, decides when an object is freed.
Attribute mutation. R objects carry attributes like names, dimensions, and classes. A thread can write to an attribute while a second thread reads it. The reader sees a partially updated attribute. Attribute data structures are not atomic.
Symbol table and string cache. R keeps a table of interned symbols and a cache of interned strings (CHARSXPs). Creating a symbol is a check-then-act sequence: look the name up, and insert it if it is missing. GNU R takes no lock around that sequence, so two threads running it at once can both insert the same name, and every comparison that relies on pointer identity then breaks.
8.3.8 Detection
ThreadSanitizer is a tool that detects data races. It instruments the program to record every memory access and every synchronization operation. When two threads access the same location, at least one access writes, and no synchronization it observed orders the two, ThreadSanitizer reports a race.
threaded-r has a ThreadSanitizer build lane, and it cannot finish a full build of R. R’s deeply recursive evaluator overruns TSan’s own shadow stack while R runs itself during the build. The configure option --disable-byte-compiled-packages skips the first step that crashes, but the build still stops with the same fault while R builds the grDevices lazy-load database. A second blocker appeared later: a build with only some files instrumented crashes in TSan’s shadow-stack setup as soon as a second interpreter thread starts. Once that option was found, and before the second blocker appeared, a two-thread spike did run under TSan and reported seven data races, every one in memory.c. The project finds races with repeated stress campaigns and a valgrind lane, and, since the R3 release candidate (2026-08-26), with TSan too: a TSan-instrumented R core, with the release build’s packages spliced in, ran a live THREAD-cluster workload, and the 946 reports it raised were worked down to zero on two runs.
ThreadSanitizer does not catch all races. It catches data races that happen to execute during testing. A race requiring a rare interleaving often never occurs in tests. It also does not detect race conditions, which are logic errors, not memory-level ones.
A race that manifests rarely in tests is a heisenbug. The bug appears and vanishes under observation. Adding logging to investigate changes thread timing. The rare interleaving that triggered the bug becomes even rarer. The bug appears to disappear. Testing cannot prove the absence of heisenbugs.
8.3.9 Prevention by construction
The best prevention is to design systems that cannot race. Rust’s type system rules out data races at compile time.
Rust distinguishes between types safe to share across threads. A type marked Send can move to another thread. A type marked Sync can be shared by multiple threads safely. The compiler enforces these properties. If a type is not Sync, the compiler rejects any attempt to share it across threads. In safe Rust, the programmer cannot introduce a data race by accident.
The borrow checker allows at most one writer to a piece of memory at any time. When a reference is borrowed for writing, no other references exist. This rule prevents data races at the type level. Two threads cannot simultaneously write to the same location, and a thread cannot write while another reads, except through types such as Mutex and the atomics, which synchronize every access.
The r-in-rust interpreter crates forbid unsafe code: the workspace lints set unsafe_code = "forbid". Only the crates that implement the R C API opt out, because calling C needs it. Safe Rust rules out data races in the interpreter’s own code. It does not rule out race conditions, which are logic errors.
In C and C++, the programmer must synchronize access manually using mutexes or atomics. Synchronization is the programmer’s job, and mistakes in it produce races that are hard to debug.
8.3.10 Tradeoffs
Synchronization protects correctness at a cost. Locking an uncontended mutex costs an atomic instruction or two. Under contention, a waiting thread can sleep in the kernel, which costs a system call and a context switch, and the lock serializes the threads that need it. Some systems use lock-free techniques to avoid the cost of locking, but lock-free code is harder to reason about and easier to get wrong.
Rust’s Send and Sync checks run at compile time and add no runtime cost. The locks and atomics they push code toward still cost what they cost in C. Outside unsafe code there is no way around the checks, and the r-in-rust interpreter crates forbid unsafe code.
The tradeoff is between compile-time proof and flexibility: Rust rejects some correct programs that it cannot prove free of data races, and C accepts incorrect ones.
8.3.11 Relevance to my work
For threaded-r. Multiple interpreters share a single process. Every place where GNU R accesses a global data structure becomes a potential race. The census found 1,574 mutable globals. Some moved to per-interpreter state, and others are protected by locks. The work is ongoing.
For r-in-rust. The Rust type system prevents data races at compile time. Each interpreter is one value owned by one thread, and the interpreter has no global mutable state, so two interpreters in one process share no mutable interpreter state to race on.
8.3.12 Open questions
- How can tooling efficiently detect race conditions in R packages with native code?
- Can tools help package authors write thread-safe R packages?
- Does threaded-r need to provide synchronization primitives to R code?
Further reading
- The Rustonomicon, Data Races and Race Conditions <https://doc.rust-lang.org/nomicon/races.html>. States what safe Rust guarantees and what it does not.
- cppreference.com, Multi-threaded executions and data races <https://en.cppreference.com/w/cpp/language/multithread#Data_races>. The C++ definition of a data race.
- ThreadSanitizer C/C++ manual <https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual>.
Where this appears
- threaded-r Multiple interpreters share a process. Race conditions become possible in environment bindings, promise forcing, reference counting, and symbol management.
- r-in-rust (rrs) Rust’s type system prevents data races at compile time. The interpreter forbids unsafe code.