Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter 4 SpinLock: is Acquire/Release synchronization required in the constructor? #62

Open
jake-ch-chen opened this issue Dec 27, 2024 · 0 comments
Labels

Comments

@jake-ch-chen
Copy link

jake-ch-chen commented Dec 27, 2024

The content that the question is about

About the constructor of our DIY SpinLock<T>

The question

So I'm wondering if the constructor SpinLock<T>::new is sound by itself, or it takes advantage of the fact that most of the ways one may communicate with other threads already have happens-before relationship semantics built-in.

Currently the constructor snippet of SpinLock is like the following:

impl<T> SpinLock<T> {
    pub const fn new(value: T) -> Self {
        Self {
            locked: AtomicBool::new(false),
            value: UnsafeCell::new(value),
        }
    }}

I'm wondering why we don't need something like this, considering there may be some move of T happening during the call?

impl<T> SpinLock<T> {
    pub const fn new(value: T) -> Self {
        let ret = Self {
            locked: AtomicBool::new(true),
            value: UnsafeCell::new(value),
        };
        ret.locked.store(false, atomic::Ordering::Release);
        ret
    }
}

Is it because for any &SpinLock<T> to be available in other threads, some sort of thread spawn or channels are ultimately required, and since the thread::spawn/Sender::send mostly likely already provide the required happens-before semantics, we don't really need to (re-)implement the happens-before relationship in our SpinLock<T>::new again?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant