Atomic Fetch Max High Water Mark
Track a high water mark across threads with AtomicU64::fetch_max, reading the previous maximum on every update without taking a lock.
Code
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let peak = Arc::new(AtomicU64::new(0));
let mut handles = Vec::new();
for sample in [12_u64, 97, 45, 130, 7] {
let peak = Arc::clone(&peak);
handles.push(thread::spawn(move || {
// fetch_max returns the value that was stored before the update
let previous = peak.fetch_max(sample, Ordering::AcqRel);
(sample, previous)
}));
}
for handle in handles {
let (sample, previous) = handle.join().unwrap();
println!("sample {sample} saw previous max {previous}");
}
println!("final high water mark: {}", peak.load(Ordering::Acquire));
}How it works
Count the function main as the entire surface area of Atomic Fetch Max High Water Mark.
A single loop drives the file — for sample in [12_u64, 97, 45, 130, 7].
Points of care
- No lockfile entry, no version pinning — the file needs nothing beyond the runtime.
Using it
Signature: fn main()
Running the file prints labeled results such as sample, final high water mark: — each operation’s effect is visible in the output.
Key statements
let (sample, previous) = handle.join().unwrap();
handles.push(thread::spawn(move || {
// fetch_max returns the value that was stored before the update
let previous = peak.fetch_max(sample, Ordering::AcqRel);
(sample, previous)
}));
Interactive Tools for This Topic
cURL to fetch ConverterTranslate a curl command into equivalent JavaScript fetch() code, handling the request method, headers, JSON or raw body, and basic auth.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Atomic Fetch Max High Water Mark print when run?
- Run it as a complete program — the output lines carry labels such as `sample`, `final high water mark:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.