Home > Backend Development > C++ > Are C Atomic Read-Modify-Write Operations Single Operations with Acquire-Release Semantics, or a Sequence of Loads and Stores?

Are C Atomic Read-Modify-Write Operations Single Operations with Acquire-Release Semantics, or a Sequence of Loads and Stores?

Barbara Streisand
Release: 2024-12-07 19:22:13
Original
310 people have browsed it

Are C   Atomic Read-Modify-Write Operations Single Operations with Acquire-Release Semantics, or a Sequence of Loads and Stores?

Memory Ordering with Atomic Read-Modify-Write Operations

In C , atomic read-modify-write (RMW) operations such as x.exchange() enforce specific ordering guarantees with respect to other loads and stores. The question arises whether these operations are considered:

  1. A single operation with acquire-release semantics
  2. An acquire load followed by a release store with additional guarantees

Standard Perspective

According to the C standard, RMW operations are treated as single operations. This is implied by their singular name and related wording.

ARM64 Implementation

In ARM64, RMW operations are implemented as a sequence of load, atomic exchange, and store instructions. While theoretically this implementation allows the store instruction to become visible before the atomic exchange, this does not affect the standard's memory ordering guarantees.

Memory Synchronization

Memory synchronization in C is primarily based on the synchronizes-with relationship between release and acquire operations. In the provided code example:

  • x.exchange(1, std::memory_order_acq_rel): The acquisition of the synchronizes-with relationship does not matter because there are no subsequent stores to x.
  • x.load(std::memory_order_acquire): The load on x does not synchronizes with anything, making it effectively relaxed.

Synchronization Analysis

As there are no other operations to synchronize with, the following sequence occurs:

  1. Store to y
  2. Load on y (relaxed)
  3. Load on x (relaxed)

Possible Output

Therefore, the code can indeed output 0, 1. The standard's perspective implies that the RMW operation is a single operation with no additional guarantees, allowing this output.

The above is the detailed content of Are C Atomic Read-Modify-Write Operations Single Operations with Acquire-Release Semantics, or a Sequence of Loads and Stores?. 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