Simple example of `compare_exchange`
- Dominant language
- Rust
- Stars
- 225
- Forks
- 33
- PR merge metrics
- No merged PRs in 30d
Description
Hi!
I appreciated this library. Kudos!!
Anyway, I didn't find any useful example of how to use the `compare_exchange` API.
Could the following example be good?
```rust
use haphazard::{AtomicPtr, HazardPointer};
pub struct C {
pub c: AtomicPtr
}
impl C {
pub fn new() -> Self {
Self {
c: AtomicPtr::from(Box::new(0))
}
}
pub fn increment_by_one(&self) {
let mut h = HazardPointer::new();
loop {
let counter = self.c.safe_load(&mut h).expect("not null");
let new_value = counter + 1;
let b = Box::new(new_value);
match self.c.compare_exchange(counter as *const usize as *mut usize, b) {
Ok(_) => break,
Err(_) => {},
}
}
h.reset_protection();
}
}
#[test]
fn test_increment_by_one() {
use std::{sync::Arc, thread};
let counter = C::new();
let counter = Arc::new(counter);
let ths: Vec<_> = (0..2)
.map(|_| {
let counter = Arc::clone(&counter);
thread::spawn(move || {
counter.increment_by_one();
counter.increment_by_one();
counter.increment_by_one();
})
})
.collect();
for th in ths {
th.join().unwrap();
}
let mut h = haphazard::HazardPointer::new();
assert_eq!(counter.c.safe_load(&mut h).unwrap(), &6);
}
```
I don't like the part `counter as *const usize as *mut usize`. That seems odd, but I didn't find a better way.
Also, I ignore the value associated with the Err in `compare_exchange`.
I appreciate your help. I'll fire a PR to integrate that example if you like it.
Contributor guide
No contributing guide indexed for this repository
Research direction
Start by locating the public compare_exchange API and the repository's existing examples or documentation conventions. Validate the proposed Rust example and address its questions about the pointer cast and ignored Err value; the work is done when a clear, runnable example demonstrates compare_exchange.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- distributed-systems
- Issue type
- Documentation
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100