简体   繁体   English

在多线程中使用不带Arc的Mutex是否安全?

[英]Is it safe to use a Mutex without Arc in multithreading?

lazy_static! {
    pub static ref A: Mutex<Vec<u8>> = Mutex::new(vec![]);
}

#[test]
fn test() {
    let mut handles = vec![];
    for _ in 0..100 {
        let handle = thread::spawn(|| for _ in 0..10000 { A.lock().unwrap().push(1); });
        handles.push(handle);
    }

    for handle in handles { handle.join().unwrap(); }
    println!("{}", A.lock().unwrap().len());
}

I got the output which was 1000000 , but I'm not sure this is a right way to collect the data in multithreading. 我得到的输出是1000000 ,但是我不确定这是否是在多线程中收集data的正确方法。

Should I change it to Arc<Mutex<_>> ? 我应该将其更改为Arc<Mutex<_>>吗?

This is safe, yes. 这是安全的,是的。 Multithreading is exactly what mutexes are for. 多线程正是互斥的目的。 Arc doesn't give you anything you need here. Arc在这里没有提供您所需的任何东西。

Note, of course, that your current code is horrendously inefficient. 当然,请注意,您当前的代码效率很低。 I hope your real use case does a lot more work between mutex locks than this. 我希望您的实际用例在互斥锁之间能做更多的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM