Home > Backend Development > C++ > How Can Atomic Operations on Doubles and Vectors Be Achieved on x86_64 Despite C Limitations?

How Can Atomic Operations on Doubles and Vectors Be Achieved on x86_64 Despite C Limitations?

Patricia Arquette
Release: 2024-11-28 06:06:19
Original
395 people have browsed it

How Can Atomic Operations on Doubles and Vectors Be Achieved on x86_64 Despite C   Limitations?

Despite the limitations of C 's std::atomic, which lacks lock-free support, x86_64 provides assembly-level support for certain atomic operations on doubles and vectors.

Atomic Double Operations on x86_64

  • Naturally-aligned loads and stores (up to 8 bytes) are atomic.
  • Atomic read-modify-write operations (RMW) require a retry loop with cmpxchg.
  • cmpxchg16b can be used for 16-byte atomic loads, stores, and RMW.

SSE/AVX Vector Operations on x86_64

While C currently lacks support for atomic AVX/SSE vector operations, there is no way to guarantee atomic transfers of 128b or 256b cache lines across the entire system.

However, certain precautions can be taken to minimize the risk of tearing when using vector loads/stores on shared arrays of aligned doubles.

Atomic 16B Load

  • Using lock cmpxchg16b with desired=expected can provide an atomic 16B load.

Atomic 16B Store and RMW

  • lock cmpxchg16b can be used for atomic 16B stores and RMW operations.

Atomic Operations on 16B Objects with 8B Halves

  • It is possible to atomically update a 16B object while reading its 8B halves independently.

Compilers and Atomic Operations

Compilers may not always generate optimal assembler code for atomic operations. For example, they may avoid direct movsd loads/stores between XMM and double registers, opting instead for roundabout methods.

The above is the detailed content of How Can Atomic Operations on Doubles and Vectors Be Achieved on x86_64 Despite C Limitations?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template