Mutex<T> ​

核心概念 ​

Mutex<T>(Mutual Exclusion,互斥锁)是 Rust 标准库中用于保护共享可变数据的同步原语,定义在 std::sync 模块中。它确保同一时刻只有一个线程能访问被保护的数据。要访问 Mutex 内部的数据,必须先调用 lock() 方法获取锁,lock() 返回一个 MutexGuard 智能指针,通过它可以读写内部数据。当 MutexGuard 离开作用域被 drop 时,锁自动释放。如果另一个线程持有锁,lock() 会阻塞当前线程直到锁可用。在多线程场景中,Mutex 通常和 Arc(原子引用计数)配合使用,Arc<Mutex<T>> 是 Rust 中共享可变状态的标准模式。

rust
use std::sync::Mutex;

fn main() {
    // 创建一个 Mutex 保护的值
    let data = Mutex::new(0);

    // lock() 获取锁,返回 MutexGuard
    {
        let mut guard = data.lock().unwrap();
        *guard += 1;  // 通过 guard 修改内部数据
        println!("值: {}", *guard);
        // guard 离开作用域,锁自动释放
    }

    // 锁已释放,可以再次获取
    {
        let guard = data.lock().unwrap();
        println!("值: {}", *guard);
    }

    // into_inner() 消耗 Mutex,取出内部值
    let final_value = data.into_inner().unwrap();
    println!("最终值: {}", final_value);
}

MutexGuard 的自动释放 ​

rust
use std::sync::Mutex;

fn main() {
    let data = Mutex::new(vec![1, 2, 3]);

    // 方式1:用代码块控制锁的范围
    {
        let mut guard = data.lock().unwrap();
        guard.push(4);
    }  // guard drop,锁释放

    // 方式2:用 drop 手动释放
    let mut guard = data.lock().unwrap();
    guard.push(5);
    drop(guard);  // 手动释放锁

    // 方式3:在表达式中使用(临时变量自动释放)
    data.lock().unwrap().push(6);
    // 这一行结束后,临时的 MutexGuard 就被 drop 了

    println!("数据: {:?}", data.lock().unwrap());

    // 常见错误:锁持有时间过长
    // let guard = data.lock().unwrap();
    // // ... 做了大量计算 ...
    // // guard 直到函数结束才释放,其他线程无法访问

    // 正确做法:尽快释放锁
    let snapshot = {
        let guard = data.lock().unwrap();
        guard.clone()  // 克隆数据后立即释放锁
    };
    // 用 snapshot 做后续操作,不持有锁
    println!("快照: {:?}", snapshot);
}

Arc<Mutex<T>> 多线程共享 ​

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

fn main() {
    // Arc<Mutex<T>> 是多线程共享可变数据的标准模式
    let counter = Arc::new(Mutex::new(0));
    let mut handles = Vec::new();

    for _ in 0..10 {
        let counter = Arc::clone(&counter);  // 克隆 Arc(增加引用计数)
        handles.push(thread::spawn(move || {
            let mut num = counter.lock().unwrap();  // 获取锁
            *num += 1;
            // MutexGuard drop,锁释放
        }));
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("最终计数: {}", *counter.lock().unwrap());  // 10

    // 共享 Vec
    let shared_list = Arc::new(Mutex::new(Vec::new()));
    let mut handles = Vec::new();

    for i in 0..5 {
        let list = Arc::clone(&shared_list);
        handles.push(thread::spawn(move || {
            let mut guard = list.lock().unwrap();
            guard.push(i);
            println!("线程{} 添加后: {:?}", i, *guard);
        }));
    }

    for h in handles {
        h.join().unwrap();
    }

    println!("最终列表: {:?}", shared_list.lock().unwrap());
}

lock 失败与中毒(Poisoning) ​

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

fn main() {
    let data = Arc::new(Mutex::new(vec![1, 2, 3]));

    // 如果持有锁的线程 panic,Mutex 会被"中毒"(poisoned)
    let data_clone = Arc::clone(&data);
    let handle = thread::spawn(move || {
        let _guard = data_clone.lock().unwrap();
        panic!("线程崩溃了!");
        // _guard 在 panic 展开时被 drop,锁被释放但标记为中毒
    });

    // 等待线程完成(会 panic)
    let _ = handle.join();

    // 中毒后 lock() 返回 Err(PoisonError)
    match data.lock() {
        Ok(guard) => println!("正常: {:?}", *guard),
        Err(poisoned) => {
            println!("Mutex 已中毒!");
            // 仍然可以获取数据(数据可能处于不一致状态)
            let guard = poisoned.into_inner();
            println!("中毒后的数据: {:?}", *guard);
        }
    }

    // 如果确定中毒后的数据仍然有效,可以用 unwrap 或直接恢复
    // 实际中大多数代码直接 unwrap(),让中毒传播
}

try_lock 非阻塞获取 ​

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

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

    let data_clone = Arc::clone(&data);
    let holder = thread::spawn(move || {
        let _guard = data_clone.lock().unwrap();
        println!("线程A: 持有锁");
        thread::sleep(Duration::from_millis(500));  // 长时间持有
        println!("线程A: 释放锁");
    });

    // 等一下让线程A先获取锁
    thread::sleep(Duration::from_millis(50));

    // try_lock:不阻塞,锁不可用时立即返回 Err
    match data.try_lock() {
        Ok(guard) => println!("主线程获取到锁: {}", *guard),
        Err(_) => println!("主线程: 锁被占用,稍后再试"),
    }

    // 轮询模式
    let mut attempts = 0;
    loop {
        attempts += 1;
        match data.try_lock() {
            Ok(guard) => {
                println!("第{}次尝试成功,值={}", attempts, *guard);
                break;
            }
            Err(_) => {
                thread::sleep(Duration::from_millis(100));
            }
        }
    }

    holder.join().unwrap();
}
方法阻塞返回适用场景
lock()阻塞直到获取锁Result<MutexGuard, PoisonError>必须访问数据
try_lock()不阻塞Result<MutexGuard, TryLockError>可选的非关键访问

避免死锁 ​

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

fn main() {
    // 死锁场景1:同一线程重复 lock(Mutex 不可重入)
    let data = Mutex::new(42);
    {
        let _guard1 = data.lock().unwrap();
        // let _guard2 = data.lock().unwrap();  // 死锁!同一线程第二次 lock
    }

    // 死锁场景2:两个 Mutex 交叉加锁
    // 线程A: lock(m1) → lock(m2)
    // 线程B: lock(m2) → lock(m1)
    // 如果 A 拿到 m1,B 拿到 m2,互相等待对方释放 → 死锁

    // 解决方案:始终按固定顺序加锁
    let m1 = Arc::new(Mutex::new("资源1"));
    let m2 = Arc::new(Mutex::new("资源2"));

    let m1_c = Arc::clone(&m1);
    let m2_c = Arc::clone(&m2);

    let h1 = thread::spawn(move || {
        let _g1 = m1_c.lock().unwrap();  // 先 m1
        let _g2 = m2_c.lock().unwrap();  // 再 m2
        println!("线程1: 持有两个锁");
    });

    let m1_c = Arc::clone(&m1);
    let m2_c = Arc::clone(&m2);

    let h2 = thread::spawn(move || {
        let _g1 = m1_c.lock().unwrap();  // 也先 m1(相同顺序)
        let _g2 = m2_c.lock().unwrap();  // 再 m2
        println!("线程2: 持有两个锁");
    });

    h1.join().unwrap();
    h2.join().unwrap();

    // 解决方案:缩小锁的粒度
    // 不要在持有锁的时候做耗时操作
    let data = Mutex::new(vec![1, 2, 3]);

    let snapshot = {
        let guard = data.lock().unwrap();
        guard.clone()  // 快速复制后释放锁
    };

    // 在没有锁的情况下做耗时计算
    let sum: i32 = snapshot.iter().sum();
    println!("总和: {}", sum);
}

基本示例 ​

用 Arc<Mutex<T>> 构建一个线程安全的共享缓存:

rust
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

// 线程安全的缓存
struct SharedCache {
    store: Arc<Mutex<HashMap<String, String>>>,
}

impl SharedCache {
    fn new() -> Self {
        SharedCache {
            store: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    fn get(&self, key: &str) -> Option<String> {
        let guard = self.store.lock().unwrap();
        guard.get(key).cloned()
    }

    fn set(&self, key: String, value: String) {
        let mut guard = self.store.lock().unwrap();
        guard.insert(key, value);
    }

    fn remove(&self, key: &str) -> Option<String> {
        let mut guard = self.store.lock().unwrap();
        guard.remove(key)
    }

    fn len(&self) -> usize {
        let guard = self.store.lock().unwrap();
        guard.len()
    }

    // 获取 Arc clone 用于跨线程
    fn clone_handle(&self) -> Arc<Mutex<HashMap<String, String>>> {
        Arc::clone(&self.store)
    }
}

impl Clone for SharedCache {
    fn clone(&self) -> Self {
        SharedCache {
            store: Arc::clone(&self.store),
        }
    }
}

fn main() {
    let cache = SharedCache::new();

    // 多个线程同时写入
    let mut handles = Vec::new();

    for i in 0..5 {
        let cache = cache.clone();
        handles.push(thread::spawn(move || {
            let key = format!("key_{}", i);
            let value = format!("value_{}", i);
            cache.set(key.clone(), value.clone());
            println!("线程{}: 写入 {} = {}", i, key, value);

            thread::sleep(Duration::from_millis(50));

            // 读取自己写的值
            if let Some(v) = cache.get(&key) {
                println!("线程{}: 读取 {} = {}", i, key, v);
            }
        }));
    }

    for h in handles {
        h.join().unwrap();
    }

    println!("\n缓存大小: {}", cache.len());

    // 读取所有缓存内容
    {
        let guard = cache.clone_handle();
        let store = guard.lock().unwrap();
        println!("\n=== 缓存内容 ===");
        for (k, v) in store.iter() {
            println!("  {} = {}", k, v);
        }
    }

    // 并发计数器
    println!("\n=== 并发计数器 ===");
    let counter = Arc::new(Mutex::new(0_u64));
    let iterations_per_thread = 10_000;
    let num_threads = 4;

    let mut handles = Vec::new();
    for _ in 0..num_threads {
        let counter = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            for _ in 0..iterations_per_thread {
                let mut count = counter.lock().unwrap();
                *count += 1;
            }
        }));
    }

    for h in handles {
        h.join().unwrap();
    }

    let final_count = *counter.lock().unwrap();
    let expected = num_threads * iterations_per_thread;
    println!("最终计数: {} (预期: {})", final_count, expected);
    println!("正确: {}", final_count == expected as u64);

    // thread::scope 版本(不需要 Arc)
    println!("\n=== 使用 thread::scope ===");
    let data = Mutex::new(Vec::new());

    thread::scope(|s| {
        for i in 0..5 {
            s.spawn(|| {
                let mut guard = data.lock().unwrap();
                guard.push(i);
            });
        }
    });
    // 所有 scoped 线程在这里保证完成

    println!("scope 结果: {:?}", data.into_inner().unwrap());
}

常见问题 ​

问题一:Mutex 和 RwLock 有什么区别?

Mutex 不区分读写,任何访问都需要独占锁。RwLock 区分读锁和写锁,多个线程可以同时持有读锁,但写锁是独占的。如果读多写少,RwLock 性能更好;如果读写频率差不多,Mutex 更简单。

问题二:为什么需要 Arc 配合 Mutex?

Mutex 本身不能跨线程共享——thread::spawn 要求 'static,直接借用局部变量的 Mutex 不满足。Arc 提供线程安全的引用计数,让多个线程共同拥有 Mutex 的所有权。用 thread::scope 时不需要 Arc,因为 scoped 线程保证在作用域结束前完成。

问题三:Mutex 中毒(poisoned)后还能用吗?

可以。PoisonError 提供了 into_inner() 方法获取 MutexGuard。但数据可能处于不一致状态(因为之前的线程 panic 了)。需要判断数据是否有效后再使用。

问题四:Rust 的 Mutex 是可重入的吗?

不是。同一线程对同一个 Mutex 调用两次 lock() 会死锁。如果需要可重入锁,可以用 parking_lot crate 的 ReentrantMutex。

适用场景 ​

  • 共享计数器:多个线程递增同一个计数
  • 共享集合:多个线程读写同一个 HashMap/Vec
  • 状态管理:多个线程共享一个状态对象
  • 缓存:多个线程共享一个缓存

注意事项 ​

  • lock() 返回 MutexGuard,离开作用域自动释放锁
  • 持有锁的时间尽可能短,避免阻塞其他线程
  • 同一线程不要对同一个 Mutex 重复 lock(会死锁)
  • 多个 Mutex 要按固定顺序加锁(避免死锁)
  • 持有锁的线程 panic 会导致 Mutex 中毒
  • thread::scope 内不需要 Arc,直接借用 Mutex 即可

总结 ​

Mutex<T> 通过互斥锁保护共享数据,确保同一时刻只有一个线程能访问。lock() 获取锁返回 MutexGuard 智能指针,通过它读写内部数据,MutexGuard drop 时自动释放锁。多线程场景中用 Arc<Mutex<T>> 共享可变状态——Arc 提供线程安全的引用计数,Mutex 提供互斥访问。持有锁的线程 panic 会导致 Mutex 中毒,后续 lock() 返回 Err。try_lock() 提供非阻塞的锁获取。使用 Mutex 时要注意持有锁的时间尽可能短、避免同一线程重复 lock、多个 Mutex 按固定顺序加锁,以防止死锁。thread::scope(Rust 1.63+)内可以直接借用 Mutex,不需要 Arc。