3 ms·
> I don't expect my compiler to go ahead and run step 3 first. You would be surprised[0]. In low level code (in some cases) you'll need memory barriers[1] to e
by conductor 10y ago
> I don't expect my compiler to go ahead and run step 3 first.
You would be surprised[0]. In low level code (in some cases) you'll need memory barriers[1] to ensure the proper order of instructions execution.
Even in higher level code your compiler's optimization algorithm may decide that it's faster to execute step 3 first if it thinks the result would be the same.
[0] https://en.wikipedia.org/wiki/Out-of-order_execution https://en.wikipedia.org/wiki/Out-of-order_execution
[1] http://irl.cs.ucla.edu/~yingdi/web/paperreading/whymb.2010.06.07c.pdf http://irl.cs.ucla.edu/~yingdi/web/paperreading/whymb.2010.0...
- planteen 10y agoOut-of-order execution always has the same answer that would occur from a single threaded perspective. There's no "thinks the result would be the same" about it - the result is the same. You get into trouble when you: 1) assuming ordering to external peripherals (e.g., memory mapped I/O) 2) assuming stores/loads are happening in a specific order (e.g., other threads either pre-empt or are simultaneously running) causing data races Your response makes it sound like a compiler could reorder functions like: x=5; x=add(x,5); x=multiply(x,10); printf("%d", x); and you could expect to get either 100 or 55 as an answer if you didn't use fences. That's not true. The answer will always be right (100) no matter what OOO, speculative execution, etc happen.
- conductor 10y agoIf you read my post carefully the "thinks the result would be the same" was about compiler optimization case, not processors' out-of-order execution. Take this example: a = 5; b = sqrt(44); return a * b; If the optimizer is sure (and strict aliasing[0] also helps to be sure in many other not so obvious cases) that the sqrt function is not using the a variable then it can swap lines 1 and 2 in the generated machine code, and the result will be the same. In your example changing lines 2 and 3 will alter the result naturally so the optimizer won't touch it. [0] http://dbp-consulting.com/tutorials/StrictAliasing.html http://dbp-consulting.com/tutorials/StrictAliasing.html