I happened to notice that, currently, official example use Arc<AtomicUsize>
to describe the usage of Atomic type, which is redundancy since Atomic type should have no issue with sharing, wrapping it into an Arc
is unnecessary.
Is it better to modify its implementation for modern Rust?
IMHO, thread::scope
should be introduced rather than Arc.
Old example:
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{hint, thread};
fn main() {
let spinlock = Arc::new(AtomicUsize::new(1));
let spinlock_clone = Arc::clone(&spinlock);
let thread = thread::spawn(move|| {
spinlock_clone.store(0, Ordering::SeqCst);
});
// Wait for the other thread to release the lock
while spinlock.load(Ordering::SeqCst) != 0 {
hint::spin_loop();
}
if let Err(panic) = thread.join() {
println!("Thread had an error: {panic:?}");
}
}
The one I proposed:
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{hint, thread};
fn main() {
let spinlock = AtomicUsize::new(1);
thread::scope(|s|{
let thread = s.spawn(|| {
spinlock.store(0, Ordering::SeqCst);
});
// Wait for the other thread to release the lock
while spinlock.load(Ordering::SeqCst) != 0 {
hint::spin_loop();
}
if let Err(panic) = thread.join() {
println!("Thread had an error: {panic:?}");
}
});
}
Is my example better?
Currently I have difficult connect to github. Thus if my example is better, pls create a PR for me. thx.
A PR is created. Currently I have no difficult clone the repo, but when I tried to view a file with my firefox, github would return a 500 error. I suppose it is something due to my nginx reverse proxy, but I don't know how to fix it.