Created
February 12, 2026 13:09
-
-
Save hsqStephenZhang/5f4797fa7043c314942e92f0ca90ca50 to your computer and use it in GitHub Desktop.
bench between CAS operations' weak and strong versions in rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use criterion::{black_box, criterion_group, criterion_main, Criterion}; | |
| use std::sync::atomic::{AtomicUsize, Ordering}; | |
| /// 显式地使用 compare_exchange_weak 来模拟 compare_exchange (strong) 的语义 | |
| /// 只有当值真的不相等时才返回 Err,虚假失败会在内部循环掉 | |
| fn compare_exchange_weak_wrapped( | |
| atomic: &AtomicUsize, | |
| current: usize, | |
| new: usize, | |
| ) -> Result<usize, usize> { | |
| loop { | |
| match atomic.compare_exchange_weak(current, new, Ordering::SeqCst, Ordering::Relaxed) { | |
| // 情况 1: 成功了,直接返回 | |
| Ok(v) => return Ok(v), | |
| // 情况 2: 失败了,检查是“真失败”还是“虚假失败” | |
| Err(actual) => { | |
| if actual != current { | |
| // 真失败:值确实被别人改了 | |
| return Err(actual); | |
| } | |
| // 虚假失败:值没变,继续循环重试 | |
| continue; | |
| } | |
| } | |
| } | |
| } | |
| fn bench_cas_semantics(c: &mut Criterion) { | |
| let mut group = c.benchmark_group("Atomic_CAS_Semantics"); | |
| let initial_val = 0; | |
| // 1. 标准 Strong 语义 (由标准库/硬件提供) | |
| group.bench_function("strong_native", |b| { | |
| let atomic = AtomicUsize::new(initial_val); | |
| b.iter(|| { | |
| let current = black_box(initial_val); | |
| let new = black_box(initial_val + 1); | |
| // 每次成功后重置,确保测试的是单次冲突/成功情况 | |
| let _ = atomic.compare_exchange(current, new, Ordering::SeqCst, Ordering::Relaxed); | |
| atomic.store(initial_val, Ordering::Relaxed); | |
| }) | |
| }); | |
| // 2. 用 Weak 封装出的 Strong 语义 (手动套循环) | |
| group.bench_function("weak_wrapped", |b| { | |
| let atomic = AtomicUsize::new(initial_val); | |
| b.iter(|| { | |
| let current = black_box(initial_val); | |
| let new = black_box(initial_val + 1); | |
| // 调用我们自己封装的函数 | |
| let _ = compare_exchange_weak_wrapped(&atomic, current, new); | |
| atomic.store(initial_val, Ordering::Relaxed); | |
| }) | |
| }); | |
| group.finish(); | |
| } | |
| criterion_group!(benches, bench_cas_semantics); | |
| criterion_main!(benches); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment