Skip to content

Instantly share code, notes, and snippets.

@jcvenegas
Created July 9, 2021 20:08
Show Gist options
  • Save jcvenegas/10534dd23de461eb9b538bd3d8011081 to your computer and use it in GitHub Desktop.
Save jcvenegas/10534dd23de461eb9b538bd3d8011081 to your computer and use it in GitHub Desktop.
Rust lock impl using atomic swap
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