本文简要介绍rust语言中 core::sync::atomic::AtomicBool.compare_and_swap 的用法。
用法
pub fn compare_and_swap( &self, current: bool, new: bool, order: Ordering) -> bool如果当前值与 current 值相同,则将值存储到 bool 。
返回值始终是前一个值。如果它等于 current ,则该值已更新。
compare_and_swap 还接受一个 Ordering 参数,该参数说明了此操作的内存顺序。请注意,即使使用 AcqRel ,操作也可能会失败,因此只执行 Acquire 加载,但没有 Release 语义。使用 Acquire 使存储部分成为此操作 Relaxed (如果发生),使用 Release 使加载部分成为 Relaxed 。
注意:此方法仅在支持原子操作的平台上可用u8.
迁移到 compare_exchange 和 compare_exchange_weak
compare_and_swap 等价于 compare_exchange,具有以下内存排序映射:
| 原版的 | 成功 | 失败 |
|---|---|---|
| Relaxed | Relaxed | Relaxed |
| Acquire | Acquire | Acquire |
| Release | Release | Relaxed |
| AcqRel | AcqRel | Acquire |
| SeqCst | SeqCst | SeqCst |
即使比较成功,compare_exchange_weak 也允许虚假失败,这允许编译器在循环中使用比较和交换时生成更好的汇编代码。
例子
use std::sync::atomic::{AtomicBool, Ordering};
let some_bool = AtomicBool::new(true);
assert_eq!(some_bool.compare_and_swap(true, false, Ordering::Relaxed), true);
assert_eq!(some_bool.load(Ordering::Relaxed), false);
assert_eq!(some_bool.compare_and_swap(true, true, Ordering::Relaxed), false);
assert_eq!(some_bool.load(Ordering::Relaxed), false);相关用法
- Rust AtomicBool.compare_exchange用法及代码示例
- Rust AtomicBool.compare_exchange_weak用法及代码示例
- Rust AtomicBool.fetch_update用法及代码示例
- Rust AtomicBool.store用法及代码示例
- Rust AtomicBool.load用法及代码示例
- Rust AtomicBool.from_mut用法及代码示例
- Rust AtomicBool.fetch_nand用法及代码示例
- Rust AtomicBool.fetch_xor用法及代码示例
- Rust AtomicBool.swap用法及代码示例
- Rust AtomicBool.as_mut_ptr用法及代码示例
- Rust AtomicBool.fetch_and用法及代码示例
- Rust AtomicBool.fetch_or用法及代码示例
- Rust AtomicBool.get_mut用法及代码示例
- Rust AtomicBool.new用法及代码示例
- Rust AtomicBool.into_inner用法及代码示例
- Rust AtomicU8.fetch_sub用法及代码示例
- Rust AtomicPtr.compare_exchange_weak用法及代码示例
- Rust AtomicU32.fetch_min用法及代码示例
- Rust AtomicI8.fetch_or用法及代码示例
- Rust AtomicI8.as_mut_ptr用法及代码示例
- Rust AtomicU8.fetch_or用法及代码示例
- Rust AtomicUsize.load用法及代码示例
- Rust AtomicI16.fetch_min用法及代码示例
- Rust AtomicI16.fetch_and用法及代码示例
- Rust AtomicU16.into_inner用法及代码示例
注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 core::sync::atomic::AtomicBool.compare_and_swap。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
