Rust 程式設計視訊教程(進階)——018_2 互斥器示例

linghuyichong發表於2020-02-08

頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

github地址:https://github.com/anonymousGiga/learn_rus...

1、執行緒間共享Mutex
(1)錯誤例子:

use std::sync::Mutex;
use std::thread;
fn main() {
    let counter = Mutex::new(0);
    let mut handles = vec![];
    for _ in 0..10 {
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }
    for handle in handles {
        handle.join().unwrap();
    }
    println!("Result: {}", *counter.lock().unwrap());
}

錯誤原因:不能將counter鎖的所有權移動到多個執行緒中。

(2)錯誤例子2:通過Rc來建立引用計數的值

use std::rc::Rc;
use std::sync::Mutex;
use std::thread;
fn main() {
    let counter = Rc::new(Mutex::new(0));
    let mut handles = vec![];
    for _ in 0..10 {
        let counter = Rc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }
    for handle in handles {
        handle.join().unwrap();
    }
    println!("Result: {}", *counter.lock().unwrap());
}

錯誤原因:Rc不是執行緒安全的

(3)例子3:使用Arc
說明: Arc是一個類似於Rc並可以安全的用於併發環境的型別,程式碼如下:

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

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();

            *num += 1;
        });
        handles.push(handle);
    }

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

    println!("Result: {}", *counter.lock().unwrap());
}

2、RefCell/Rc 與 Mutex/Arc 的相似性
(1)Mutex提供內部可變性,類似於RefCell;
(2)RefCell/Rc是非執行緒安全的,而Mutex/Arc是執行緒安全的。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

令狐一衝

相關文章