0Pricing
Learn Rust Coding · Lesson

Sharing State with Arc/Mutex

Safe shared data.

Why Shared State Is Hard

Sometimes message passing is not enough and multiple threads truly need to read and write the same data. Rust will not let you share a mutable value across threads without protection, because that would risk a data race.

The two tools you combine are:

  • Arc for shared ownership across threads.
  • Mutex for safe, exclusive mutation.

Rc Is Not Thread-Safe

Rc gives shared ownership but only on a single thread. Its reference count is not synchronized, so the compiler refuses to send it between threads. For multi-threaded sharing you need Arc (Atomically Reference Counted).

Arc behaves like Rc but updates its count with atomic operations, making clones safe across threads.

use std::sync::Arc;

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

All lessons in this course

  1. mpsc Channels
  2. Sharing State with Arc/Mutex
  3. Scoped Threads
  4. Crossbeam Channels
← Back to Learn Rust Coding