Is it sound to cast &AtomicU32 to &[AtomicU16; 2]?

If I understand correctly, that really matter is atomic operations, so it looks like such casts should be sound.

1 Like

All atomic operations that happen in parallel must either be entirely disjoint or overlap exactly. So the cast itself is ok, but accessing the AtomicU32 and an AtomicU16 that overlap like this in parallel is not.

4 Likes

Thank you! But wouldn't it make the cast unsound since it allows users to break the restriction in safe code?

Could you please link some official docs which covers the restriction in more detail?

The conversion is sound in the sense that it doesn't immediately trigger UB, but you are correct that releasing the references to safe code would not be ok. The code using the references would need to be in the same crate as the unsafe block doing the conversion to reason about it.

Rust itself doesn't say anything about this topic, but it does say that it uses the C/C++ memory model for atomics. The paper Mixed-Size Concurrency: ARM, POWER, C/C++11, and SC on the topic has the following to say about the situation in C/C++.

At the C/C++11 language level, we have extended the previous C/C++11 axiomatic model to cover non-racy mixed-size accesses, but one would like a solid compilation scheme result to provide assurance about both this and the hardware models, and supporting mixed-size atomics and mixtures of atomic and non-atomic accesses represents another open problem for the design of C/C++11 models

So making this well-defined is an open problem, and should be treated as undefined behavior today.

(I don't have anything more official than this paper.)

6 Likes

How about intel's documentation for x86?

2 Likes

Interestingly enough, it looks like Linux relies on atomic operations on the same memory with different sizes and it works fine in practice. I think I've heard about it from somewhere else as well, but I can't remember from where exactly.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.