Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does sequenced-before relation in C++11 prevent compiler/CPU reordering?

I know that generally a modern C++ compiler and processor will perform certain optimizations by sometimes reordering instructions for better performance.

C++11 introduces a sequenced before relation. And if instruction A comes before instruction B in program order, we say that A is sequenced before B.

int data = 0;
bool ready = 0;

// A is sequenced before B
data = 6;      // A
ready = true;  // B

C++11 also defines a requirement for sequenced before relation.

Given any two evaluations A and B, if A is sequenced before B, then the execution of A shall precede the execution of B.

This puzzles me. To me, it conflicts with out-of-order executions because the reordering may break the above required property. E.g., when store to ready happens before store to data.

Does the definition above stop instruction reordering? (I'm pretty sure it's not. But what did I miss?)

like image 870
Eric Z Avatar asked Aug 13 '14 13:08

Eric Z


1 Answers

Since "sequenced before" (in this instance) only applies to a single thread:

Sequenced before is an asymmetric, transitive, pair-wise relation between evaluations executed by a single thread [...]

§1.9 [intro.execution]

And since the compiler/CPU can perform whatever transformations they wish provided the code executes as if it followed the standard:

A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible executions of the corresponding instance of the abstract machine with the same program and the same input.

§1.9 [intro.execution]

Arbitrary reorderings may (or may not) occur.

Note that special rules apply between threads. See §1.10 [intro.multithread].

like image 149
Robert Allan Hennigan Leahy Avatar answered Oct 24 '22 06:10

Robert Allan Hennigan Leahy