Created
June 25, 2020 19:50
-
-
Save tstellanova/9b8ec9f1a6d4d928931d171c7b3b914a to your computer and use it in GitHub Desktop.
Simple mutex using spin lock with atomics in no_std rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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