[英]Why do Rust's `Atomic*` types use non-mutable functions to mutate the value?
I notice that Rust's Atomic*
structs have functions which modify the value, such as fetch_add
. 我注意到Rust的
Atomic*
结构具有修改值的函数,例如fetch_add
。 For instance, I can write this program: 例如,我可以写这个程序:
use std::sync::atomic::{AtomicUsize, Ordering};
struct Tester {
counter: AtomicUsize
}
impl Tester {
fn run(&self) {
let counter = self.counter.fetch_add(1, Ordering::Relaxed);
println!("Hi there, this has been run {} times", counter);
}
}
fn main() {
let t = Tester { counter: AtomicUsize::new(0) };
t.run();
t.run();
}
This compiles and runs fine, but if I change the AtomicUsize
to a normal integer, it will (correctly) fail to compile due to mutability concerns: 这编译并运行正常,但如果我将
AtomicUsize
更改为正常整数,由于可变性问题,它将(正确)无法编译:
struct Tester {
counter: u64
}
impl Tester {
fn run(&self) {
self.counter = self.counter + 1;
println!("Hi there, this has been run {} times", self.counter);
}
}
It wouldn't be very useful if it didn't work this way. 如果它不以这种方式工作就不会有用。 With
&mut
references, only one can exist at a time, and no &
references at that time, so the whole question of atomicity of operation would be moot. 使用
&mut
引用,一次只能存在一个,并且当时没有&
引用,所以整个操作原子性问题都没有实际意义。
Another way of looking at it is &mut
are unique references, and &
aliasable references. 查看它的另一种方法是
&mut
是唯一引用和&
别名引用。 For normal types, mutation can only safely occur if you have a unique reference, but atomic types are all about mutation (via replacement) without needing a unique reference. 对于普通类型,只有具有唯一引用才能安全地发生变异,但原子类型都是关于变异(通过替换)而不需要唯一引用。
The naming of &
and &mut
has been a fraught matter, with much fear, uncertainty and doubt in the community and documents like Focusing on Ownership explaining how things actually are. &
和&mut
的命名一直是一个令人担忧的问题,在社区中存在很多恐惧,不确定和怀疑,而像Focusing on Ownership这样的文件解释了事情的实际情况。 The language has ended up staying with &
and &mut
, but &mut
is actually about uniqueness rather than mutability (it's just that most of the time the two are equivalent). 语言最终与
&
和&mut
保持一致,但是&mut
实际上是关于唯一性而不是可变性(只是大多数情况下两者是等价的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.