-
Notifications
You must be signed in to change notification settings - Fork 13.9k
Closed
Labels
A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-bugCategory: This is a bug.Category: This is a bug.
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.
Metadata
Metadata
Assignees
Labels
A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-bugCategory: This is a bug.Category: This is a bug.