Tópicos importantes de Rust

Rust Arc and Mutex

Let several threads change one value safely: Arc shares it, Mutex guards it.

  • Avançado
  • 3 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • Mutex and lock
  • Arc::clone
  • Why the count is always right
4 threads x 1000 increments
  1. 1Arc::cloneeach thread gets a handle
  2. 2lock()one at a time
  3. 3*value += 1safe update
  4. 44000always

One lock, many owners

When threads must change the same value, a Mutex makes sure only one of them touches it at a time. Arc lets every thread own a handle to that Mutex.

Arc::clone gives each thread its own handle to the same counter. lock waits until no other thread holds the lock and returns a guard; the lock is released when the guard goes out of scope. Four threads each add 1000, so the result is always 4000.

Pontos-chave

  1. lock gives one thread access at a time.
  2. The lock is released when the guard goes out of scope.
  3. Arc lets every thread own a handle.

Exemplo executável de Rust

Rust
Executar código →
main.rs
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..4 {
        let counter = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            for _ in 0..1000 {
                let mut value = counter.lock().unwrap();
                *value += 1;
            }
        }));
    }

    for handle in handles {
        handle.join().unwrap();
    }
    println!("final count: {}", *counter.lock().unwrap());
}
Gerar um botão Run para este exemplo Resultado da execução
final count: 4000

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios