|
|
Subscribe / Log in / New account

Load/Store tearing in this day and age?

Load/Store tearing in this day and age?

Posted Jul 17, 2019 9:32 UTC (Wed) by comex (subscriber, #71521)
In reply to: Load/Store tearing in this day and age? by pr1268
Parent article: Who's afraid of a big bad optimizing compiler?

> IMO loads and stores should be atomic at the assembly level (if not at the metal) for an n-bit value on an n-bit architecture. Just my $0x02.

They typically *are* guaranteed to be atomic at the assembly level, but only if the pointer is properly aligned.

You can see this more easily if you use C11 atomics, which are more explicit about what guarantees they provide. For example, this source code:

	#include <stdatomic.h>
	int load(_Atomic int *ptr) {
		return atomic_load_explicit(ptr, memory_order_relaxed);
	}

compiles to this assembly (GCC targeting x86-64):

	load:
			mov     eax, DWORD PTR [rdi]
			ret

All C11 atomic loads/stores are guaranteed to be, well, atomic, but GCC has decided to emit a plain mov instruction. In fact this is valid, because x86 has an architectural guarantee that regular movs (64-bit and smaller) to and from aligned pointers are atomic. (And GCC is allowed to assume that `ptr` is aligned, because using it is undefined behavior if not.) Most common architectures work the same.

On the other hand, many uses of atomics want a stronger memory ordering, e.g. memory_order_acquire. On x86, this *still* just generates a plain mov instruction, because x86 has very strong ordering guarantees for all accesses. But on other architectures it tends to require additional synchronization or a different instruction.


to post comments


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds