Closed
Description
Page: https://doc.rust-lang.org/std/sync/atomic/fn.fence.html
use std::sync::atomic::AtomicBool;
use std::sync::atomic::fence;
use std::sync::atomic::Ordering;
// A mutual exclusion primitive based on spinlock.
pub struct Mutex {
flag: AtomicBool,
}
impl Mutex {
pub fn new() -> Mutex {
Mutex {
flag: AtomicBool::new(false),
}
}
pub fn lock(&self) {
while !self.flag.compare_and_swap(false, true, Ordering::Relaxed) {}
// This fence synchronizes-with store in `unlock`.
fence(Ordering::Acquire);
}
pub fn unlock(&self) {
self.flag.store(false, Ordering::Release);
}
}
The CAS function would return the original value of the flag
, so the loop would exit when the original value of flag
is true
, i.e. when it is locked.