当前位置:网站首页>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
边栏推荐
- Fact final variable and final variable
- Complete example demonstration of creating table to page - joint table query
- Collections multiple parameter sorting
- [leetcode 67] sum of two binary numbers
- Understanding and use of tp50, tp90 and tp99
- [leetcode 54] spiral matrix
- [transfer] MySQL: how many rows of data can InnoDB store in a B + tree?
- [leetcode 459] duplicate substring
- H. Are You Safe? Convex hull naked problem
- Definition of C class and method
猜你喜欢
Chapter 4 of line generation - linear correlation of vector systems
Unsupervised denoising - [tmi2022] ISCL: dependent self cooperative learning for unpaired image denoising
In depth understanding of the relationship between dncblevel and noise denoising in the paper
線性代數第一章-行列式
自动控制(韩敏版)
Algèbre linéaire chapitre 1 - déterminants
RPC must know and know
JDBC connection database
Preparedstatement prevents SQL injection
Mysql database foundation
随机推荐
Type conversion in C #
JDBC tool class encapsulation
Plane semi intersecting plate
The bottom implementation principle of thread - static agent mode
Contrôle automatique (version Han min)
Calculation (enter the calculation formula to get the result)
[leetcode 383] ransom letter
6.Reversal
JSP syntax and JSTL tag
Framework analysis 2 Source code - login authentication
Import of data
Use of multithreaded executors
lambda expressions
Explain of MySQL optimization
RPC must know and know
Animation - Introduction to keyframes
On traversal of binary tree
[leetcode 228] summary interval
PyTorch笔记——观察DataLoader&用torch构建LeNet处理CIFAR-10完整代码
Fundamentals of SQL: first knowledge of database and SQL - installation and basic introduction - Alibaba cloud Tianchi