0Pricing
Learn Rust Coding · Lesson

Sharing with Arc and Mutex

Safely mutate shared state.

The Need for Shared State

Sometimes several threads must read or update the same data. Moving ownership to a single thread is not enough.

Rust gives you safe shared ownership across threads with Arc, and safe mutation with Mutex. Together they enable shared, mutable state.

Arc: Atomic Reference Counting

Arc stands for atomically reference counted. It is like Rc, but its counter uses atomic operations, so it is safe across threads.

Cloning an Arc does not copy the data. It only increments the count and returns another handle to the same value.

use std::sync::Arc;

fn main() {
    let shared = Arc::new(vec![1, 2, 3]);
    let clone = Arc::clone(&shared);
    println!("{:?} {:?}", shared, clone);
}

All lessons in this course

  1. Spawning Threads
  2. Moving Data into Threads
  3. Sharing with Arc and Mutex
  4. Joining and Collecting Results
← Back to Learn Rust Coding