Custom SpinLock implementation

โš“ Rust    ๐Ÿ“… 2026-01-18    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 6      

surdeus

Hello. I am reading through the excellent "Rust - Atomics and Locks" book by Mara Bos.

There is a simple implementation for a SpinLock: rust-atomics-and-locks/src/ch4_spin_lock/s1_minimal.rs at main ยท m-ou-se/rust-atomics-and-locks ยท GitHub

I want to create a minimal usage example for it. This is my current example which still throws errors. Can someone help me out here?
Thanks in advance :slight_smile:

use std::{cell::UnsafeCell, time::Duration};

mod spin_lock {
    use std::sync::atomic::{
        AtomicBool,
        Ordering::{Acquire, Release},
    };

    pub struct SpinLock {
        locked: AtomicBool,
    }

    impl SpinLock {
        #[allow(clippy::new_without_default)]
        pub const fn new() -> SpinLock {
            SpinLock {
                locked: AtomicBool::new(false),
            }
        }

        pub fn lock(&self) {
            while !self.locked.swap(true, Acquire) {
                std::hint::spin_loop();
            }
        }

        pub fn unlock(&self) {
            self.locked.store(false, Release);
        }
    }
}

struct SyncWrapper<T>(UnsafeCell<T>);

unsafe impl<T: Send> Sync for SyncWrapper<T> {}

fn main() {
    let data = SyncWrapper(UnsafeCell::new(String::new()));
    let lock = spin_lock::SpinLock::new();

    std::thread::scope(|s| {
        s.spawn(|| {
            for _ in 0..5 {
                lock.lock();

                // doing work on `data`
                std::thread::park_timeout(Duration::from_micros(123));
                unsafe {
                    (*data.0.get()).push_str("thread 0\n");
                }

                lock.unlock();
            }
        });
        s.spawn(|| {
            for _ in 0..10 {
                lock.lock();

                // doing work on `data`
                std::thread::park_timeout(Duration::from_micros(51));
                unsafe {
                    (*data.0.get()).push_str("thread 1\n");
                }

                lock.unlock();
            }
        });
    });
    println!("{}", unsafe { &*data.0.get() });
}

2 posts - 2 participants

Read full topic

๐Ÿท๏ธ Rust_feed