19.3 Arc, Mutex, and Interior Mutability

RUSTSTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-11-18
Before this page Borrowing and Lifetimes

19.3.1 The problem: ownership of shared data

Ownership by default is simple: one owner, one responsibility for cleanup. But real programs need to share data. A closure captures variables from its parent scope. A cache lives in a struct but is read from many code paths. Rust provides explicit tools for sharing, and each tool trades off memory cost, runtime overhead, and thread safety.

In a garbage-collected system, the garbage collector owns all reachable data. Code borrows it freely. The collector keeps it alive as long as something refers to it. This works but requires a tracing collector and the overhead it brings.

In Rust, ownership is explicit and a value has one owner, but sharing still happens. A symbol table is created once and accessed from many places. A work-stealing queue is owned by the scheduler but accessed by many workers.

For these cases, Rust provides Rc<T> and Arc<T>. Both are reference-counted pointers. When you clone the pointer, the reference count increments. When the pointer is dropped, the count decrements. When it reaches zero, the value is freed. Reference counting is explicit and incremental. It has no GC pause.

Reference counting is an old technique, used in Objective-C, CPython and many other systems. Rust makes it explicit in the types, so you can see which data is reference counted. The compiler stops an Rc from crossing threads, but it does not stop reference cycles: two Rc values that point at each other are never freed.

19.3.2 Rc for single-threaded code

An Rc<T> is a reference-counted pointer. Multiple holders can own an Rc pointing to the same value. The value is freed when the last Rc is dropped.

let x = Rc::new(42);
let y = x.clone();  // reference count increments to 2
let z = x.clone();  // reference count increments to 3
// at the end of the scope, z is dropped first: count decrements to 2
// then y: count decrements to 1
// then x: count reaches 0 and 42 is freed

Rc is cheap. Cloning copies a pointer and adds one to an ordinary, non-atomic integer. If two threads updated that integer at the same time, increments could be lost and the value freed while still in use, which is why Rc cannot cross thread boundaries.

rrs does not build its object model on Rc or Arc; its design rules forbid an Rc-based object model. Closures, environments and the symbol table live inside one interpreter, which refers to its objects through integer handles and frees them with its own collector. Arc appears only in small places, such as a cache of parsed closure formals.

19.3.3 Arc for multi-threaded code

An Arc<T> (atomic reference counted) is the same as Rc<T> but with atomic operations on the count. Multiple threads can hold Arc pointers to the same value. The count is safe to mutate from any thread.

let x = Arc::new(42);
let y = x.clone();
// spawn a thread
std::thread::spawn(move || {
    let z = y.clone();  // safe to clone in another thread
    println!("{}", z);  // z is dropped here
});                     // y moved into the thread, and is dropped when it finishes
// x is dropped at the end of this scope
// when all Arc are dropped, 42 is freed

The cost is higher than Rc. An atomic increment costs more than a plain one, and when several threads clone and drop the same Arc, the cache line holding the count moves back and forth between their cores. For a shared heap or a shared symbol table, that is the price of sharing. For objects that are never shared, it buys nothing.

19.3.4 Interior mutability: RefCell and Mutex

The borrow checker says: you can share a value (with &T), but you cannot mutate it. You can mutate a value (with &mut T), but only from one place at a time. Shared and mutable borrows never coexist.

Sometimes a design needs mutation through a shared reference. A cache inside a data structure. A reference count inside an object. A status flag. Rust provides tools to bypass the compile-time check and defer it to runtime.

RefCell<T> works for single-threaded code. You borrow the inner value at runtime.

let x = RefCell::new(42);
let r = x.borrow();     // shared borrow at runtime
let r2 = x.borrow();    // another shared borrow
drop(r); drop(r2);      // both borrows end here
let mut w = x.borrow_mut();  // exclusive borrow at runtime
*w = 100;

The drop line is required. r and r2 are guard values that end their borrow when they are dropped, not at their last use, so without that line borrow_mut finds them still live. If a shared borrow and a mutable borrow overlap, RefCell panics. The check moves from compile time to runtime. The cost is a runtime borrow count that must be checked on every borrow.

Interior mutability is a design pattern that appears in caches, counters, and status flags. A value is immutable from the outside but mutable from the inside.

struct Cache {
    data: RefCell<HashMap<String, Value>>,
}

impl Cache {
    fn lookup(&self, key: &str) -> Option<Value> {
        self.data.borrow().get(key).cloned()
    }

    fn insert(&self, key: String, value: Value) {
        self.data.borrow_mut().insert(key, value);
    }
}

insert takes &self, not &mut self, but it can still mutate the internal HashMap. The RefCell enforces that only one mutable borrow exists at a time, but the check is at runtime. For a symbol table or a heap allocator, interior mutability allows immutable references while the internal state changes.

Mutex<T> is the multithreaded version. It holds a lock. When you call .lock(), it waits until the lock is acquired, then gives you exclusive access.

let x = Mutex::new(42);
let mut guard = x.lock().unwrap();
// guard holds the lock and gives access to the value
*guard = 100;
// when guard is dropped, the lock is released

Multiple threads can call .lock() on the same Mutex. Only one will proceed at a time. The others wait. Mutex ensures safety but adds contention. If many threads compete for the same lock, throughput drops.

When data must be shared and mutable across threads, Arc<Mutex<T>> is the pattern. The Arc lets both threads hold a pointer to the same data. The Mutex ensures that only one thread accesses it at a time. The cost is the cost of Arc cloning plus the cost of locking.

Reference counting and locking have real costs. Arc uses atomic operations on the reference count, and threads that clone and drop the same Arc keep moving its cache line between cores, which also slows any other data on that line. Mutex adds contention. If many threads need the same data, they queue at the lock and only one proceeds at a time. An uncontended lock costs about one atomic operation; a contended one can put the waiting thread to sleep in the kernel. For an interpreter shared across threads, both costs would apply: with the heap behind an Arc<Mutex<_>>, every allocation and every collection would wait on the lock. This is why per-interpreter heaps matter for parallelism.

Per-interpreter heaps and thread-local allocators can remove most of this lock contention. The trade-off is more complex initialization and shutdown.

19.3.5 RwLock for read-heavy workloads

A RwLock<T> is a variant of Mutex that allows many readers or one writer. If data is read much more often than written, RwLock can improve throughput.

let x = RwLock::new(42);
let r1 = x.read().unwrap();   // first reader
let r2 = x.read().unwrap();   // second reader, no contention
drop(r1); drop(r2);           // the writer waits until every reader is gone
let mut w = x.write().unwrap();  // exclusive writer
*w = 100;

As with RefCell, the drop line is required. A thread that asks for the write lock while it still holds a read guard waits for itself: on Windows this snippet hangs without that line, and the standard library documents that the call might panic instead.

The cost is higher than Mutex if contention is low. If contention is high and most accesses are reads, RwLock can be faster.

The R symbol table is read-heavy. Most code reads symbols. Few places define new ones. For an interpreter shared across threads, a RwLock would likely fit the symbol table better than a Mutex.

19.3.6 Other systems

Most languages leave sharing to the programmer or to the runtime.

CPython counts references on every object. In the default build, a Global Interpreter Lock (GIL), one mutex for each interpreter, lets only one thread at a time run that interpreter’s Python bytecode, which among other things keeps those counts consistent. Python 3.13 added an optional free-threaded build (PEP 703) that removes the GIL and uses biased reference counting instead.

Java uses a tracing GC and locks for mutable shared state. Programmers must synchronize mutable fields explicitly. The language does not help prove that synchronization is correct.

Go encourages goroutines to communicate by sending values through channels instead of sharing mutable data. Goroutines can still share memory, and the compiler does not stop them from racing on it.

Rust gives the programmer a choice. Single-threaded code uses Rc<RefCell<T>> with no atomics. Multithreaded code uses Arc<Mutex<T>> or Arc<RwLock<T>>. Each choice has a clear cost.

19.3.7 Failure modes

A common mistake is to panic while holding a lock. The mutex is then poisoned, and later attempts to lock it return an error. Poisoning warns the next user that the data may be half-updated.

let x = Mutex::new(42);
std::thread::scope(|s| {
    let worker = s.spawn(|| {
        let mut guard = x.lock().unwrap();
        *guard = 100;
        panic!("oops");  // the guard drops during the panic: x is poisoned
    });
    let _ = worker.join();  // Err: the worker panicked
});
let guard = x.lock();  // Err(PoisonError)

The panic happens on a worker thread because a panic on the main thread would end the program before the last line ran.

Another mistake is to deadlock. Thread A holds a lock and waits for a lock that Thread B holds. Thread B waits for the lock that Thread A holds. Both threads wait forever.

These bugs exist in all multithreaded systems. Rust does not prevent them. Safe Rust does prevent data races: two threads accessing the same memory with no synchronization, at least one of them writing. It does not prevent race conditions in general, such as a check and an update that another thread slips between.

19.3.8 Performance implications and alternatives

r-in-rust currently avoids shared state between interpreters. When an interpreter is created, it owns a unique heap, symbol table, and string cache, and no other interpreter accesses them. The heap therefore needs no lock, its objects need no atomic counts, and allocation never contends with another interpreter.

The cost is that interpreters are isolated. One interpreter cannot directly call another, so data must be serialized and copied, which is a real cost for some workloads. If a future version of rrs needed shared interpreters, the types would change: Arc<Mutex<Heap>> would appear wherever the heap is touched, and every allocation would contend for it. This is why the design choice is made early. Because the types make sharing explicit, sharing cannot be added a piece at a time without the cost showing up in every lock and every atomic operation.

Some systems use lock-free data structures instead of Mutex. A lock-free queue allows multiple threads to push and pop without locks, with atomic operations coordinating access. Lock-free structures can be faster under contention but are harder to reason about, because correctness depends on memory-ordering guarantees. Most code uses Mutex first, then moves to lock-free only if measurements show it is necessary. Rust provides std::sync::atomic::AtomicUsize and related types for lock-free code. Every atomic operation takes an explicit Ordering argument, but the compiler does not check that the ordering chosen is strong enough, and lock-free structures that manage memory usually need unsafe code to free nodes safely.

Further reading

Where this appears

  • r-in-rust (rrs) Shared interpreters require Arc and Mutex. Current design avoids this cost by giving each interpreter its own owner thread.

Where to go next

Back to top