当前位置:网站首页>Rust 的多线程安全引用 Arc
Rust 的多线程安全引用 Arc
2022-04-23 05:45:00 【许野平】
Rust 的多线程安全引用 Arc
作者: 许野平
1 Arc 与 Rc 几乎一样,但是多线程安全的
Arc 与 Rc 类似,唯一不同的地方在于 Arc 是多线程安全的。参见下面的例子:
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 可以打破只读的魔咒
Arc、Rc 都是只读的共享。但是,这个所谓的只读,仅仅是语法层面的。我们可以构造语法结构上是只读的,但实际上允许修改的数据类型。Mutex 就是一个这样的引用类型。看代码吧:
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, .. }
版权声明
本文为[许野平]所创,转载请带上原文链接,感谢
https://yeping.blog.csdn.net/article/details/123053447
边栏推荐
- Common sense of thread pool
- 1. Calculate a + B
- Example of reentrant lock thread waiting to wake up
- Supply chain service terms
- 20 excellent plug-ins recommended by idea
- JDBC connection database
- Problems and solutions of database migration
- Programming record - picture rotation function SciPy ndimage. Simple use and effect observation of rotate()
- PyTorch入门小笔记——利用简单例子观察前向传播各个层输出的size
- [leetcode 350] intersection of two arrays II
猜你喜欢
随机推荐
D. Optimal partition segment tree optimization DP
線性代數第二章-矩陣及其運算
Programming training
[leetcode 19] delete the penultimate node of the linked list
Customized communication between threads (reentrantlock)
DBCP usage
Custom exception class
JSP syntax and JSTL tag
lambda expressions
1. Calculate a + B
[leetcode 228] summary interval
Exception handling: grab and throw model
Three ways to create threads
Definition of C class and method
Preparedstatement prevents SQL injection
ThreadLocal. Threadlocalmap analysis
线代第四章-向量组的线性相关
线性代数第三章-矩阵的初等变换与线性方程组
[transfer] MySQL: how many rows of data can InnoDB store in a B + tree?
Export of data






![Denoising paper - [noise2void, cvpr19] noise2void learning denoising from single noise images](/img/9d/487c77b5d25d3e37fb629164c804e2.png)


