当前位置:网站首页>Multi thread safe reference arc of rust

Multi thread safe reference arc of rust

2022-04-23 18:03:00 Xu Yeping

Rust Multithread safe reference Arc

author : Xu Yeping

1 Arc And Rc Almost the same as , But multithreading is safe

Arc And Rc similar , The only difference is Arc Is multithreaded safe . See the example below :

use std::sync::Arc;
use std::thread;

fn main() {
    
    let nums = Arc::new(vec![0, 1, 2, 3, 4]);
    let mut childs = vec![];
    for n in 0..5 {
    
        let ns = nums.clone();
        let c = thread::spawn(move || println!("{:?}", ns[n]));
        childs.push(c);
    }
    for c in childs {
    
        c.join().unwrap();
    }
}
-------------------------------------------------------------------------------
>cargo run
0
2
4
1
3

2 Arc Can break the read-only spell

Arc、Rc Are read-only shares . however , This so-called read-only , Only at the grammatical level . We can construct syntactically read-only , But the data types that are actually allowed to be modified .Mutex Is such a reference type . Look at the code :

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

fn main() {
    
    let nums = Arc::new(Mutex::new(vec![]));
    let mut childs = vec![];
    for n in 0..5 {
    
        let ns = nums.clone();
        let c = thread::spawn(move || {
    
            let mut v = ns.lock().unwrap();
            v.push(n);
        });
        childs.push(c);
    }
    for c in childs {
    
        c.join().unwrap();
    }
    println!("{:?}", nums);
}
-------------------------------------------------------------------------------
>cargo run
Mutex {
     data: [0, 1, 3, 2, 4], poisoned: false, .. }

版权声明
本文为[Xu Yeping]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230544498442.html