Created
July 9, 2021 20:08
-
-
Save jcvenegas/10534dd23de461eb9b538bd3d8011081 to your computer and use it in GitHub Desktop.
Rust lock impl using atomic swap
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 std::sync::atomic::AtomicBool; | |
use std::sync::atomic::Ordering; | |
use std::thread; | |
struct Lock { | |
lock: AtomicBool, | |
} | |
impl Lock { | |
fn lock(&self) { | |
while self.lock.swap(true, Ordering::Acquire) {} | |
} | |
fn unlock(&self) { | |
self.lock.store(false, Ordering::Release); | |
} | |
} | |
fn main() { | |
let mut handles = vec![]; | |
static mut SH_MEM: i32 = 1; | |
static L: Lock = Lock { | |
lock: AtomicBool::new(false), | |
}; | |
for _ in 0..10 { | |
let handle = thread::spawn(|| unsafe { | |
L.lock(); | |
println!("Modify {}", SH_MEM); | |
SH_MEM += 1; | |
L.unlock(); | |
}); | |
handles.push(handle); | |
} | |
for handle in handles { | |
handle.join().unwrap(); | |
} | |
unsafe { | |
println!("Result: {}", SH_MEM); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment