liveBook · Manning

Atomicity

As explained in Learn Rust in a Month of Lunches

An atomic operation is an indivisible computer operation that appears to other threads as either fully completed or not performed.

Atomicity means an operation is indivisible: other threads cannot observe it halfway through. They see it either fully completed or not performed. section 12.3

This matters when threads update shared data. Without atomic protection, two threads can read the same value, both add one, and accidentally lose an update. section 12.3

Counting safely across threads

Arc shares ownership between threads, while Mutex protects access to the value. In the example, two threads each increment a shared number ten times, producing 20 instead of a smaller, unpredictable result. section 12.3

use std::sync::{Arc, Mutex};
 
fn main() {
    let my_number = Arc::new(Mutex::new(0));
 
    let cloned_1 = Arc::clone(&my_number);
    let cloned_2 = Arc::clone(&my_number);
 
    let thread1 = std::thread::spawn(move || {    #1
        for _ in 0..10 {
            *cloned_1.lock().unwrap() += 1;       #2
        }
    });
 
    let thread2 = std::thread::spawn(move || {    #3
        for _ in 0..10 {
            *cloned_2.lock().unwrap() += 1;
        }
    });
 
    thread1.join().unwrap();
    thread2.join().unwrap();
    println!("Value is: {my_number:?}");
    println!("Exiting the program");
}

Shows Arc cloning, thread creation, locking, and atomic updates to shared state. section 12.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines indivisibility and demonstrates lost updates, but defers processor-level implementation details.
Examples
Uses concurrent counter increments and an Arc-wrapped Mutex to demonstrate lost and preserved updates.
What it assumes
Assumes basic thread access and ownership ideas while explaining atomicity and Arc in plain language.
What you can do after
Apply atomicity via Arc and Mutex when multiple threads update shared data.
How it connects
Connects atomicity with threads, Arc, Mutex, shared ownership, and thread safety.

Also explained in

Compare how 13 books explain atomicity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.