Quantcast
Channel: Can I perform arithmetic operations on an atomic variable directly? - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by zwol for Can I perform arithmetic operations on an atomic variable directly?

$
0
0

Compound assignments to variables with atomic types are explicitly allowed in C2011: quoting N1570 §6.15.6.2p3

A compound assignment of the form E1 op= E2 is equivalent to the simple assignment expression E1 = E1 op (E2), except that the lvalue E1 is evaluated only once, and with respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation. If E1 has an atomic type, compound assignment is a read-modify-write operation with memory_order_seq_cst memory order semantics. [footnote 113]

Emphasis mine. Footnote 113 goes on to give a specific example of how E1 op= E2 can be translated into <stdatomic.h> primitive operations when E1 is an atomic type.

The other operators that I'm confident one may apply to atomic types are postfix ++ and --, which are also guaranteed to perform an atomic read-modify-write (§6.5.2.4), and simple assignment, which is guaranteed to perform an atomic load or store as appropriate (§6.2.6.1).

Caution:Prefix++ and -- are not guaranteed to perform an atomic read-modify-write (compare 6.5.2.4 with 6.5.3.1).

I read this sentence of 6.2.6.1

Loads and stores of objects with atomic types are done with memory_order_seq_cst semantics.

as implying that is valid to use an atomic lvalue as an operand to most other operators, and an atomic load is performed, after which the value is not treated specially. Don't quote me on this part.

C++ may have different rules. I will leave exegesis of the C++ standard to someone else.


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>