Важные темы Rust
Rust Arc and Mutex
Let several threads change one value safely: Arc shares it, Mutex guards it.
Что вы узнаете
- Mutex and lock
- Arc::clone
- Why the count is always right
4 threads x 1000 increments
- 1
Arc::cloneeach thread gets a handle - 2
lock()one at a time - 3
*value += 1safe update - 4
4000always
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.
Главное
- lock gives one thread access at a time.
- The lock is released when the guard goes out of scope.
- Arc lets every thread own a handle.
Пример на Rust, который можно запустить
Rust
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());
}
final count: 4000Практика
Откройте пример в онлайн-компиляторе, измените значение или добавьте строку и попробуйте предсказать вывод до запуска. Затем намеренно сломайте код и прочитайте сообщение компилятора.
Закончили этот урок?
Отметьте его как изученный, чтобы следить за прогрессом.
Ваш прогресс сохранён в этом браузере Войдите, чтобы он был доступен на всех устройствах.
Попрактикуйтесь на задаче
Примените материал этого урока к реальной задаче. Каждая задача запускается в браузере, с мгновенными тестами и разбором от ИИ.
Все задачи