Loading RustViz Engine...
Implement a low-latency spinlock using AtomicBool and compare_exchange_weak.
This problem is currently in blueprint template mode. Once the concept foundation is finalized, live in-browser WebAssembly compilation and test assertion runners will be enabled here.
use std::sync::atomic::{AtomicBool, Ordering};
pub struct SpinLock {
locked: AtomicBool,
}
impl SpinLock {
pub fn new() -> Self { Self { locked: AtomicBool::new(false) } }
pub fn lock(&self) {
while self.locked.compare_exchange_weak(
false, true, Ordering::Acquire, Ordering::Relaxed
).is_err() {
std::hint::spin_loop();
}
}
pub fn unlock(&self) {
self.locked.store(false, Ordering::Release);
}
}