本文簡要介紹rust語言中 core::sync::atomic::AtomicBool.compare_exchange
的用法。
用法
pub fn compare_exchange( &self, current: bool, new: bool, success: Ordering, failure: Ordering) -> Result<bool, bool>
如果當前值與 current
值相同,則將值存儲到 bool
。
返回值是指示是否寫入新值並包含先前值的結果。成功時,此值保證等於 current
。
compare_exchange
采用兩個 Ordering
參數來說明此操作的內存順序。 success
說明了與 current
比較成功時發生的讀取-修改-寫入操作所需的順序。 failure
說明了比較失敗時發生的加載操作所需的順序。使用 Acquire
作為成功排序使存儲成為此操作的一部分 Relaxed
,並使用 Release
使成功加載 Relaxed
。失敗排序隻能是 SeqCst
、 Acquire
或 Relaxed
並且必須等於或弱於成功排序。
注意:此方法僅在支持原子操作的平台上可用u8
.
例子
use std::sync::atomic::{AtomicBool, Ordering};
let some_bool = AtomicBool::new(true);
assert_eq!(some_bool.compare_exchange(true,
false,
Ordering::Acquire,
Ordering::Relaxed),
Ok(true));
assert_eq!(some_bool.load(Ordering::Relaxed), false);
assert_eq!(some_bool.compare_exchange(true, true,
Ordering::SeqCst,
Ordering::Acquire),
Err(false));
assert_eq!(some_bool.load(Ordering::Relaxed), false);
相關用法
- Rust AtomicBool.compare_exchange_weak用法及代碼示例
- Rust AtomicBool.compare_and_swap用法及代碼示例
- 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_exchange。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。