Skip to content

Instantly share code, notes, and snippets.

@tstellanova
Created June 25, 2020 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tstellanova/9b8ec9f1a6d4d928931d171c7b3b914a to your computer and use it in GitHub Desktop.
Save tstellanova/9b8ec9f1a6d4d928931d171c7b3b914a to your computer and use it in GitHub Desktop.
Simple mutex using spin lock with atomics in no_std rust
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
struct MyStruct {
...
/// A mutability lock
mut_lock: AtomicBool,
}
impl Struct {
fn lock_me(&mut self) {
while self
.mut_lock
.compare_and_swap(false, true, Ordering::Acquire)
!= false
{
while self.mut_lock.load(Ordering::Relaxed) {
core::sync::atomic::spin_loop_hint();
}
}
}
fn unlock_me(&mut self) {
self.mut_lock
.compare_and_swap(true, false, Ordering::Acquire);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment