ARM and x86-64: No Guaranteed Atomic Types
Contrary to the initial assumption, the C/C language standards provide no guarantees of atomic operations for any specific data type, even on 64-bit computers.
Atomic Access via Signals vs. Threads
It's crucial to distinguish between two notions of atomicity:
GCC Implementations on ARM and x86-64
While modern CPUs like ARMv8 and x86-64 may guarantee atomic access for certain operations, these guarantees are not reflected at the language level. GCC and other compilers can optimize code in ways that violate these hardware-level atomicities, as demonstrated by the following example:
volatile uint32_t x; uint32_t foo(void) { return (x >> 8) & 0xffff; }
Even though x is a 32-bit variable, GCC compiles foo as two separate 16-bit loads, which could result in a non-atomic read if x is modified concurrently.
Reliance on std::atomic or _Atomic
The only way to ensure atomic operations in C and C is to explicitly use the std::atomic (C ) or _Atomic (C) types, which provide the necessary synchronization mechanisms to guarantee thread-safe access.
The above is the detailed content of Do C/C Standards Guarantee Atomic Operations for Any Data Type on ARM and x86-64 Architectures?. For more information, please follow other related articles on the PHP Chinese website!