rust_rsm/common/
spin_lock.rs

1#![allow(non_camel_case_types)]
2#![allow(non_snake_case)]
3#![allow(non_upper_case_globals)]
4
5use std::sync::atomic::{AtomicBool,Ordering};
6use std::hint;
7
8pub struct spin_lock_t {
9    locked:AtomicBool,
10}
11impl spin_lock_t {
12    pub fn new()->Self {
13        Self{ locked:AtomicBool::new(false)}
14    }
15
16    #[inline(always)]
17    pub fn lock(&self) {
18        while self.locked.compare_exchange(false, true, Ordering::SeqCst, Ordering::Relaxed).is_err() {
19            hint::spin_loop();
20        } 
21    }
22
23    #[inline(always)]
24    pub fn unlock(&self) {
25        while self.locked.compare_exchange(true, false, Ordering::SeqCst, Ordering::Relaxed).is_err() {
26            hint::spin_loop();
27        } 
28    }
29    pub fn value(&self)->bool {
30        self.locked.load(Ordering::Acquire)
31    }
32
33}
34
35impl Drop for spin_lock_t {
36    fn drop(&mut self) {
37        if self.locked.load(Ordering::Acquire)==true {
38            self.unlock()
39        }
40       
41    }
42}