Skip to content

Should operations on atomics which mutate via raw pointers accept a mutable reference to self? #50368

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

Closed
vext01 opened this issue May 1, 2018 · 4 comments

Comments

@vext01
Copy link
Contributor

vext01 commented May 1, 2018

Hi,

I was looking at the AtomicU32 documentation. The signature for compare_and_swap is:

pub fn compare_and_swap(&self, current: u32, new: u32, order: Ordering) -> u32

I found this curious, as clearly this operation may mutate the u32 inside. So why is it not accepting an &mut self?

Looking at the implementation, I see why this works. It boils down to a call to atomic_compare_exchange, which is unsafe thus (I think) allowing the immutable reference to coerce to a *mut.

But should the outward facing interface accept an &mut self to:

  • Aid the mental model of the programmer?
  • Prevent the ability to hold multiple mutable references.

Thoughts?

@vext01 vext01 changed the title Should operations on atomics which mutate via raw pointers accept a mutible reference to self? Should operations on atomics which mutate via raw pointers accept a mutable reference to self? May 1, 2018
@sfackler
Copy link
Member

sfackler commented May 1, 2018

You can only obtain a &mut self if you have unique access to the value. The entire point of the atomic types is to be used in contexts where multiple threads have concurrent access to the value.

@vext01
Copy link
Contributor Author

vext01 commented May 1, 2018

You can only obtain a &mut self if you have unique access to the value.

Yeah, you're right. But you can see why I find the interface counter-intuitive?

Perhaps in parallel universe (no pun intended) there would be a way of sharing mutable references to atomics between threads...

@sfackler
Copy link
Member

sfackler commented May 1, 2018

At one point the language behaved like that: 4c62486, and there was discussion of renaming &mut to &only: rust-lang/rfcs#58.

@vext01
Copy link
Contributor Author

vext01 commented May 1, 2018

OK, I suppose this issue is a dud then. Sorry for the noise.

@vext01 vext01 closed this as completed May 1, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants