Home > Backend Development > C++ > Do C/C Standards Guarantee Atomic Operations for Any Data Type on ARM and x86-64 Architectures?

Do C/C Standards Guarantee Atomic Operations for Any Data Type on ARM and x86-64 Architectures?

DDD
Release: 2024-12-15 14:29:31
Original
448 people have browsed it

Do C/C   Standards Guarantee Atomic Operations for Any Data Type on ARM and x86-64 Architectures?

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:

  • Atomic with respect to signals: Ensures signal safety, allowing correct reads for the updated value after a signal interrupt within the same thread.
  • Atomic with respect to threads: Ensures consistency of data across multiple threads, preventing corruption during concurrent access.

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template