← Вернуться к курсу: Rust from scratch

Shared state: Arc and Mutex

Видео скоро появится

Channels are ideal when data flows in one direction, but sometimes several threads need access to the same data: a global counter, a cache, a list of results. For those cases Rust offers two pieces that combine: Mutex<T>, which guarantees that only one thread accesses the data at a time, and Arc<T>, a pointer that lets several threads own the same data. This lesson explains why you need both and how the compiler protects you from misusing them.

Mutex<T>: one access at a time

Mutex means mutual exclusion. The data lives inside the Mutex, and to touch it you must ask for the lock with lock(), which returns a Result with a guard (MutexGuard). While you hold the guard, no other thread can get in; when the guard goes out of scope, the lock is released automatically. It is the same ownership idea: the release does not depend on you remembering to call unlock, because there is no unlock. The guard behaves like a mutable reference to the inner data, and you modify it with *.

rust
use std::sync::Mutex;

fn main() {
    let counter = Mutex::new(0);

    {
        let mut guard = counter.lock().unwrap();
        *guard += 1;
        *guard += 1;
    } // guard dropped here: the lock is released

    println!("counter = {:?}", counter);
    println!("value = {}", *counter.lock().unwrap());
}

Arc<T>: shared owners across threads

If you try to give the same Mutex to several threads with move, the first takes it and the second cannot. You need a shared owner. Rc<T> does something similar within a single thread, but it is not safe across threads and the compiler forbids it. Arc<T> (Atomic Reference Counted) is: it counts how many owners there are with atomic operations and frees the data when the last one disappears. Cloning an Arc does not copy the data, it only increments the count and gives you another pointer to the same data. The classic pattern is Arc<Mutex<T>>.

rust
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = Vec::new();

    for _ in 0..8 {
        let counter = Arc::clone(&counter); // another owner, same data
        handles.push(thread::spawn(move || {
            for _ in 0..1000 {
                let mut n = counter.lock().unwrap();
                *n += 1;
            }
        }));
    }

    for h in handles {
        h.join().unwrap();
    }
    println!("total = {}", *counter.lock().unwrap()); // always 8000
    println!("owners now = {}", Arc::strong_count(&counter));
}

The result is always 8000, no matter in which order the threads run. Compare with other languages, where forgetting the lock produces a different number on each run and the bug can go unnoticed for months. In Rust you cannot forget: the data is inside the Mutex, and the only way to it goes through lock(). And if you try to pass an Rc, the compiler answers "Rc<...> cannot be sent between threads safely", thanks to the marker traits Send and Sync, which describe which types are safe to move or share between threads.

rust
// Does NOT compile on purpose: Rc cannot be sent between threads
use std::rc::Rc;
use std::thread;

fn main() {
    let shared = Rc::new(5);
    let copy = Rc::clone(&shared);
    let h = thread::spawn(move || {
        println!("{copy}");
    });
    h.join().unwrap();
}

Good practices

  • Hold the lock for as little time as possible: do the heavy work outside the lock.
  • Avoid taking two locks at once in different order in different threads: it can cause a deadlock, which Rust does not prevent.
  • For simple counters, atomic types (AtomicUsize) are cheaper than a Mutex.
  • If data is read a lot and written little, there is RwLock.
  • Prefer channels when the data flow is natural.
rust
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let list = Arc::new(Mutex::new(Vec::new()));
    let mut handles = Vec::new();

    for i in 1..=5u32 {
        let list = Arc::clone(&list);
        handles.push(thread::spawn(move || {
            let mut v = list.lock().unwrap();
            v.push(i);
            v.push(i * 10);
            v.push(i * 100);
        }));
    }
    for h in handles {
        h.join().unwrap();
    }

    let mut result = list.lock().unwrap().clone();
    result.sort();
    println!("{} items: {:?}", result.len(), result);
    println!("sum = {}", result.iter().sum::<u32>());
}

Проверьте себя

Вопрос 1 из 4

What is Mutex<T> for?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →