【Rust】Shared-State Concurrency

Shared-State Concurrency

channel类似于single ownership. 而shared memory类似与multiple ownership. multiple ownership是难于管理的. smarter pointer也是multiple ownership的.

Rust的type system和ownership rules帮助实现正确的multiple ownership管理。

Using Mutexes to Allow Access to Data from One Thread at a Time

Mutex是mutual exclusion的缩写。mutex内部有一个锁,访问数据前,先持有锁,其他线程就不能再访问这个数据了。mutex通过locking system来实现对数据的保护。

使用mutex的两条规则:

  • 访问数据前要先持有锁;
  • 访问数据后,要记得释放锁,这样其他线程才能访问该数据。

Rust的type system和ownership rule,保证了mutex的正确使用。

The API of Mutex

Mutex<T>是智能指针;其lock()成员返回类型为MutexGuard的智能指针;MutexGuard实现了Deref接口来获取其内部数据;也实现了Drop接口来释放其内部的锁。

Sharing a Mutex Between Multiple Threads

我们无法把mutex的所有权move到多个线程中。所以需要借用引用计数的方式来实现多个所有权。

Multiple Ownership with Multiple Threads

Rc<T>在多线程中共享是非安全的。Rc<T>clone接口被调用时,它将引用计数加一;当其克隆消亡时,它将引用计数减一。但是,Rc<T>没有提供原子操作行为,多线程并发时,有可能发生Rc<T>的引用计数被同时修改。

所以,需要一种具有原子操作能力的RC.

Atomic Reference Counting with Arc

atomically reference counted

为什么所有的基本类型不实现为原子操作的呢?因为这样做有性能损失。

示例代码:

use std::sync::{Arc, Mutex};
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!("Resule {}", *counter.lock().unwrap());

}

Similarities Between RefCell/Rc and Mutex/Arc

Mutex<T>并不能防止逻辑错误,如死锁(两个线程互相等待对方持有的锁释放)。

参考资料

Shared-State Concurrency - The Rust Programming Language (rust-lang.org)

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-03-24 02:52:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-24 02:52:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-24 02:52:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-24 02:52:03       18 阅读

热门阅读

  1. 计算机二级考试注意事项(Python程序设计篇)

    2024-03-24 02:52:03       18 阅读
  2. perl:获取同花顺数据--业绩预告

    2024-03-24 02:52:03       20 阅读
  3. Hive在虚拟机中的部署

    2024-03-24 02:52:03       18 阅读
  4. C++语句,空语句,复合语句

    2024-03-24 02:52:03       19 阅读
  5. SQL题:

    SQL题:

    2024-03-24 02:52:03      16 阅读
  6. Python 类的学习

    2024-03-24 02:52:03       16 阅读
  7. 洛谷 P1011 [NOIP1998 提高组] 车站

    2024-03-24 02:52:03       17 阅读
  8. kafka 01

    kafka 01

    2024-03-24 02:52:03      17 阅读