【问题标题】:Why Mutex was designed to need an Arc in Rust为什么 Mutex 被设计为需要 Rust 中的 Arc
【发布时间】:2019-10-27 16:50:31
【问题描述】:

如果使用Mutex<T> 的唯一原因是并发代码,即多线程,为什么Mutex<T> 需要Arc<T>?首先将Mutex<T> 别名为原子引用不是更好吗?我使用https://doc.rust-lang.org/book/ch16-03-shared-state.html 作为参考。

【问题讨论】:

    标签: rust mutex smart-pointers interior-mutability


    【解决方案1】:

    您不需要Arc 即可使用MutexlockMutex 上最常用的方法)的签名是 pub fn lock(&self) -> LockResult<MutexGuard<T>>,这意味着您需要引用 Mutex

    借用检查器出现问题。在传递对可能比原始Mutex 寿命更长的线程的引用时,它无法证明某些保证。这就是你使用Arc 的原因,它保证里面的值和最后一个Arc 一样长。

    use lazy_static::lazy_static; // 1.3.0
    use std::sync::Mutex;
    use std::thread::spawn;
    
    lazy_static! {
        static ref M: Mutex<u32> = Mutex::new(5);
    }
    
    fn a(m: &Mutex<u32>) {
        println!("{}", m.lock().unwrap());
    }
    
    fn b(m: &Mutex<u32>) {
        println!("{}", m.lock().unwrap());
    }
    
    fn main() {
        let t1 = spawn(|| a(&M));
        let t2 = spawn(|| b(&M));
    
        t1.join().unwrap();
        t2.join().unwrap();
    }
    

    (Playground)

    【讨论】:

    猜你喜欢
    • 2021-02-23
    • 1970-01-01
    • 2016-09-07
    • 2020-04-14
    • 2015-02-16
    • 2019-07-15
    • 2022-09-23
    • 1970-01-01
    • 2011-01-20
    相关资源
    最近更新 更多