Home >Backend Development >C++ >Which C and C Types Exhibit Naturally Atomic Behavior on a 64-Bit x86-64 System?

Which C and C Types Exhibit Naturally Atomic Behavior on a 64-Bit x86-64 System?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 07:40:11985browse

Which C and C   Types Exhibit Naturally Atomic Behavior on a 64-Bit x86-64 System?

Which C and C Types Are Naturally Atomic on a 64-Bit Computer?

Unlike language standards, GNU C and GNU C compilers treat atomicity based on specific architectures. While C11 and C 11 introduce _Atomic types and std::atomic<> types respectively, this article focuses solely on naturally atomic reads and writes, excluding atomic increment, decrement, or compound assignment.

Atomicity Guarantees on 64-Bit Linux Computers

On a 64-bit Linux computer with an x86-64 processor, the following types have naturally atomic reads and writes:

  • int
  • _Atomic_word

However, it's important to note that even these types are not definitively automatically atomic according to the language standards.

Understanding Atomicity

There are two main senses of "atomic":

  • Atomic with respect to signals: Ensures that signal handlers invoked during different instruction execution will only see the old or new value of a volatile sig_atomic_t variable.
  • Atomic with respect to threads: Guarantees that concurrent access to an object will result in a correct value being seen by all threads. To achieve this, _Atomic or std::atomic types are necessary.

Compiler Optimizations and Atomicity

Just because a type is naturally atomic at the hardware level does not mean that the compiler will always use atomic instructions to access it. Optimizations may lead to non-atomic access, even for data types that are known to be atomic on the target hardware.

For example, a load from a 32-bit integer on x86 is atomic, but a compiler may use a 16-bit partial load or store that is not guaranteed to be atomic.

Conclusion

In summary, there are no types in C or C that are definitively automatically atomic on a 64-bit computer. To ensure atomic access, it is crucial to use _Atomic or std::atomic types or rely on documentation to verify atomic guarantees for specific architectures and compilers.

The above is the detailed content of Which C and C Types Exhibit Naturally Atomic Behavior on a 64-Bit x86-64 System?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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