Should C90-compatible compilers take into account processor reordering?

Consider the following code snippet:

volatile int a; volatile int b; int x; void func() { a = 1; x = 0; /* dummy statement */ b = 2; } 

In this code snippet, assignment x represents a point in the sequence. Therefore, according to the C90 standard, access to mutable variable a must be completed before access to b is started. When translating this code fragment to x86-64 assembler, the function body is transformed as follows:

 movl $1, a(%rip) movl $0, x(%rip) movl $2, b(%rip) 

Now, when this code is executed, the CPU can change the memory access order, thereby violating the standard C requirement, which is performed to access a and b in order. So, is this translation wrong, and does the compiler need to insert memory barriers to ensure order?

Edit: Consider the case where a and b are variables shared by two threads. In this case, the synchronization protocol between the two streams can be based on the fact that access to a and b occurs in order. Thus, when the CPU reorders access, it may violate this protocol (I'm not really trying to implement such a protocol, I'm just wondering what the correct interpretation of the C standard is).

+4
source share
1 answer

Processors can reorder instructions, but they must make sure that the result is the same as if they were not .

+6
source

Source: https://habr.com/ru/post/1388060/


All Articles