Skip to content

Instantly share code, notes, and snippets.

@pidb
Created July 17, 2022 12:50
Show Gist options
  • Save pidb/ad93cd006a732c8ad31ed89bb2848639 to your computer and use it in GitHub Desktop.
Save pidb/ad93cd006a732c8ad31ed89bb2848639 to your computer and use it in GitHub Desktop.
use std::io::Write;
use std::sync::atomic::{self, AtomicU8};
use std::sync::Arc;
use std::thread::{self};
struct SpinLock {
flag: AtomicU8,
}
impl SpinLock {
pub fn new() -> Self {
SpinLock {
flag: AtomicU8::new(0),
}
}
pub fn lock(&self) {
loop {
match self.flag.compare_exchange_weak(
0,
1,
atomic::Ordering::AcqRel,
atomic::Ordering::Relaxed,
) {
Ok(v) => {
assert_eq!(v, 0);
break;
}
Err(v) => {
assert_eq!(v, 1);
continue;
}
}
}
}
pub fn unlock(&self) {
self.flag.store(0, atomic::Ordering::Release);
}
}
fn main() {
let lock = Arc::new(SpinLock::new());
let a_lock = lock.clone();
let a = thread::spawn(move || {
a_lock.lock();
for i in 0..10 {
thread::sleep(std::time::Duration::from_millis(100));
print!("{} ", i);
_ = std::io::stdout().flush();
}
a_lock.unlock();
});
let b_lock = lock.clone();
let b = thread::spawn(move || {
b_lock.lock();
for i in 10..20 {
thread::sleep(std::time::Duration::from_millis(100));
print!("{} ", i);
_ = std::io::stdout().flush();
}
b_lock.unlock();
});
_ = a.join();
_ = b.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment