Chủ đề Rust quan trọng

Rust Arc and Mutex

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

  • Nâng cao
  • Đọc trong 3 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • 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.

Những điểm quan trọng

  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.

Ví dụ Rust chạy được

Rust
Chạy code →
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());
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
final count: 4000

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách