Skip to content
All insights

Academy

Slide 1 · Sampul. Judul serif dua baris. Standfirst sans 34 px biru tua. Kaki: tanggal kiri, sumber kanan. A Commit Is N

Discover how Rust solves the classic readers-writers concurrency problem at compile time using shared (&T) and exclusive (&mut T) references—zero data races.

5 min read

Slide 1 · Sampul. Judul serif dua baris. Standfirst sans 34 px biru tua. Kaki: tanggal kiri, sumber kanan. A Commit Is N
On this page

In concurrent programming, there's a problem so fundamental it has a name: the readers-writers problem. Multiple threads can safely read shared data simultaneously, but if any thread writes while others read (or write), you get a data race—undefined behavior that corrupts data, crashes programs, and produces bugs that are nearly impossible to reproduce in testing.

Every language solves this differently. C++ says "use mutexes and hope you don't forget." Java says "use synchronized and accept the performance hit." Go says "share memory by communicating" but doesn't enforce it. Each solution is runtime-based—violations are caught (maybe) during execution, not during compilation.

Rust solves it at compile time with two rules applied to references:

  1. Any number of shared references (&T) can coexist. Multiple readers are safe.

  2. An exclusive reference (&mut T) cannot coexist with any other reference. A writer needs exclusive access.

These rules are the readers-writers solution, encoded in the type system and verified at compile time. If your code compiles, it's free from data races involving references. No mutexes needed for reference-based sharing. No sanitizers needed to detect violations. No prayer needed for production stability.

At RantAI, these two rules are the foundation of our concurrent data processing. Shared references let multiple analysis stages read the same dataset simultaneously. Exclusive references let transformation stages modify data with guaranteed isolation. This article, drawn from Chapter 10 of our guide "The Rust Programming Language," explores shared and exclusive references in depth.

Shared References: Multiple Readers#

Rust
fn analyze(data: &[f64]) -> f64 {
    data.iter().sum::<f64>() / data.len() as f64
}

fn find_max(data: &[f64]) -> f64 {
    data.iter().cloned().fold(f64::NEG_INFINITY, f64::max)
}

fn main() {
    let dataset = vec![1.0, 2.5, 3.7, 4.2, 5.8];
    
    // Multiple shared references — all can read simultaneously
    let mean = analyze(&dataset);
    let max = find_max(&dataset);
    
    println!("Mean: {:.2}, Max: {:.1}", mean, max);
    println!("Original data: {:?}", dataset);  // Still valid
}

Shared references (&T) guarantee that the data won't change while you're reading it. This is stronger than C++'s const&—in C++, another part of the code might modify the data through a non-const reference or pointer. In Rust, if shared references exist, no mutable access is possible, period.

Exclusive References: One Writer, No Readers#

Rust
fn normalize(data: &mut Vec<f64>) {
    let max = data.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
    for value in data.iter_mut() {
        *value /= max;
    }
}

fn main() {
    let mut dataset = vec![2.0, 4.0, 6.0, 8.0, 10.0];
    normalize(&mut dataset);  // Exclusive access — no other refs can exist
    println!("Normalized: {:?}", dataset);  // [0.2, 0.4, 0.6, 0.8, 1.0]
}

Exclusive references (&mut T) guarantee that no other code can access the data while you're modifying it. This prevents the most dangerous concurrency bug—reading partially-written data—at compile time.

The Rules Enforced#

Rust
fn main() {
    let mut data = vec![1, 2, 3];
    
    // ALLOWED: Multiple shared references
    let r1 = &data;
    let r2 = &data;
    println!("{:?} {:?}", r1, r2);
    
    // ALLOWED: One exclusive reference (after shared refs are done)
    let r3 = &mut data;
    r3.push(4);
    println!("{:?}", r3);
    
    // NOT ALLOWED: Shared + exclusive simultaneously
    // let r4 = &data;
    // let r5 = &mut data;  // COMPILE ERROR
    // println!("{:?}", r4);
}

References vs C++ Pointers#

Feature Rust &T C++ const T& C++ T* Can be null No No Yes Can dangle No (lifetime system) Yes Yes Guarantees immutability Yes (enforced) No (const_cast) No Prevents aliased mutation Yes (compiler) No No Data race prevention Yes (compile-time) No No

References in Concurrent Code#

Rust
use std::thread;

fn main() {
    let data = vec![1, 2, 3, 4, 5, 6, 7, 8];
    
    // Scoped threads can borrow data safely
    thread::scope(|s| {
        let (left, right) = data.split_at(data.len() / 2);
        
        let h1 = s.spawn(|| -> i32 { left.iter().sum() });
        let h2 = s.spawn(|| -> i32 { right.iter().sum() });
        
        let total = h1.join().unwrap() + h2.join().unwrap();
        println!("Parallel sum: {}", total);
    });
    
    println!("Data still available: {:?}", data);
}

Multiple threads can hold shared references to the same data simultaneously. The compiler verifies that no thread has mutable access, preventing data races without any runtime synchronization.

Broader Implications: Compile-Time Concurrency Safety#

At RantAI, the shared/exclusive reference distinction eliminates an entire category of concurrency bugs. Our data analysis functions take &[T] parameters, guaranteeing they can run in parallel without synchronization. Our transformation functions take &mut [T], guaranteeing exclusive access. The compiler verifies that we never mix the two—no analyzer runs while a transformer is active.

Practical Applications & Strategic Takeaways#

For newcomers: &T means "I'm reading, others can read too." &mut T means "I'm writing, nobody else can touch this." These two concepts cover all safe data access patterns.

For concurrent programmers: The shared/exclusive distinction IS the readers-writers solution. If your concurrent code uses only references (no unsafe, no raw pointers), data races are impossible.

For API designers: Functions that take &T are inherently parallelizable—multiple callers can invoke them simultaneously on the same data. Functions that take &mut T require sequential access. Choose the weaker requirement.

Our Commitment to Open Knowledge#

RantAI is committed to open education. Shared and exclusive references are covered in Chapter 10 of our guide, "The Rust Programming Language," freely available online.

Explore these concepts further: https://trpl.rantai.dev

Support Our Mission & Get Your Handbook#

Have you experienced the "aha moment" where you realized Rust's borrowing rules ARE the readers-writers solution? Share when it clicked!

#RustLang #SharedReferences #ExclusiveAccess #DataRaces #RantAI #LearnRust #Concurrency #BorrowChecker #CompileTimeSafety #SystemsProgramming

Next article

Slices and Buffer Safety: How Rust Made the Buffer Overflow Extinct