Re: C aggregate passing (Rust kernel policy)

From: Andy Lutomirski
Date: Wed Feb 26 2025 - 15:35:08 EST


On Wed, Feb 26, 2025 at 12:27 PM Kent Overstreet
<kent.overstreet@xxxxxxxxx> wrote:

> E.g. if you're doing a ringbuffer with head and tail pointers shared
> between multiple threads, you no longer do that with bare integers, you
> use atomics (even if you're not actually using any atomic operations on
> them).
>

FWIW, as far as I'm concerned, this isn't Rust-specific at all. In my
(non-Linux-kernel) C++ code, if I type "int", I mean an int that
follows normal C++ rules and I promise that I won't introduce a data
race. (And yes, I dislike the normal C++ rules and the complete lack
of language-enforced safety here as much as the next person.) If I
actually mean "a location in memory that contains int and that I
intend to manage on my own", like what "volatile int" sort of used to
mean, I type "atomic<int>". And I like this a *lot* more than I ever
liked volatile. With volatile int, it's very very easy to forget that
using it as an rvalue is a read (to the extent this is true under
various compilers). With atomic<int>, the language forces [0] me to
type what I actually mean, and I type foo->load().

I consider this to be such an improvement that I actually went through
and converted a bunch of code that predated C++ atomics and used
volatile over to std::atomic. Good riddance.

(For code that doesn't want to modify the data structures in question,
C++ has atomic_ref, which I think would make for a nicer
READ_ONCE-like operation without the keyword volatile appearing
anywhere including the macro expansion.)

[0] Okay, C++ actually gets this wrong IMO, because atomic::operator
T() exists. But that doesn't mean I'm obligated to use it.