为什么许多原始类型都有一个“Atomic*”类型,而不是通用的“Atomic<T>”?
Why is there one `Atomic*` type for many primitive type instead of a generic `Atomic<T>`?
查看 the std::sync::atomic
module,可以看到一堆不同的 Atomic*
类型,例如 AtomicU32
、AtomicI16
等等。这是为什么?
Rust 有泛型,而且——正如我所见——可以添加一个泛型 Atomic<T>
,其中 T
受模块中定义的某些特征的限制(在 Java -ish 命名:Atomicable
)。该特征将由可以以原子方式处理的类型实现,用户可以只使用 Atomic<u32>
而不是 AtomicU32
.
为什么没有通用的 Atomic<T>
?为什么要有一堆不同的类型呢?
AtomicU8
(例如)的目的是使用底层硬件执行 atomic instructions, e.g. on x86 the CMPXCHG
instruction。
最初的 RFC #1505 suggested a Atomic<T>
type. One of the main concern was,人们会以意想不到的方式使用 T
,例如使用无法支持的 Atomic<[u8; 32]>
,因为缺少支持这些的硬件。
提出了使用 Mutex
的 fallback/workaround,但感觉像是作弊,因为编译器对于不同的 T
会有不同的行为。
It was finally closed in favor of RFC #1543 引入了我们今天所知的 Atomic{I,U}{8,16,32,64} 类型。
然后在 PR #33048 and stabilized in PR #56753 中实现,即 Rust 1.34.0。
为确保底层硬件真正支持类型具有 cfg 属性的原子操作,例如AtomicI8
是 #[cfg(target_has_atomic = "8")]
, for AtomicI16
it is #[cfg(target_has_atomic = "16")]
等等。
查看 the std::sync::atomic
module,可以看到一堆不同的 Atomic*
类型,例如 AtomicU32
、AtomicI16
等等。这是为什么?
Rust 有泛型,而且——正如我所见——可以添加一个泛型 Atomic<T>
,其中 T
受模块中定义的某些特征的限制(在 Java -ish 命名:Atomicable
)。该特征将由可以以原子方式处理的类型实现,用户可以只使用 Atomic<u32>
而不是 AtomicU32
.
为什么没有通用的 Atomic<T>
?为什么要有一堆不同的类型呢?
AtomicU8
(例如)的目的是使用底层硬件执行 atomic instructions, e.g. on x86 the CMPXCHG
instruction。
最初的 RFC #1505 suggested a Atomic<T>
type. One of the main concern was,人们会以意想不到的方式使用 T
,例如使用无法支持的 Atomic<[u8; 32]>
,因为缺少支持这些的硬件。
提出了使用 Mutex
的 fallback/workaround,但感觉像是作弊,因为编译器对于不同的 T
会有不同的行为。
It was finally closed in favor of RFC #1543 引入了我们今天所知的 Atomic{I,U}{8,16,32,64} 类型。
然后在 PR #33048 and stabilized in PR #56753 中实现,即 Rust 1.34.0。
为确保底层硬件真正支持类型具有 cfg 属性的原子操作,例如AtomicI8
是 #[cfg(target_has_atomic = "8")]
, for AtomicI16
it is #[cfg(target_has_atomic = "16")]
等等。