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

Example Mutex in std::sync::atomic::fence is wrong #74808

Closed
pca006132 opened this issue Jul 27, 2020 · 1 comment · Fixed by #74910
Closed

Example Mutex in std::sync::atomic::fence is wrong #74808

pca006132 opened this issue Jul 27, 2020 · 1 comment · Fixed by #74910
Labels
A-docs Area: documentation for any part of the project, including the compiler, standard library, and tools C-bug Category: This is a bug.

Comments

@pca006132
Copy link

Page: https://doc.rust-lang.org/std/sync/atomic/fn.fence.html

use std::sync::atomic::AtomicBool;
use std::sync::atomic::fence;
use std::sync::atomic::Ordering;

// A mutual exclusion primitive based on spinlock.
pub struct Mutex {
    flag: AtomicBool,
}

impl Mutex {
    pub fn new() -> Mutex {
        Mutex {
            flag: AtomicBool::new(false),
        }
    }

    pub fn lock(&self) {
        while !self.flag.compare_and_swap(false, true, Ordering::Relaxed) {}
        // This fence synchronizes-with store in `unlock`.
        fence(Ordering::Acquire);
    }

    pub fn unlock(&self) {
        self.flag.store(false, Ordering::Release);
    }
}

The CAS function would return the original value of the flag, so the loop would exit when the original value of flag is true, i.e. when it is locked.

@jyn514 jyn514 added A-docs Area: documentation for any part of the project, including the compiler, standard library, and tools C-bug Category: This is a bug. labels Jul 27, 2020
@RalfJung
Copy link
Member

That's a good catch, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-docs Area: documentation for any part of the project, including the compiler, standard library, and tools C-bug Category: This is a bug.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants