问题
Let std::atomic<std::int64_t> num{0};
be defined somewhere accessible/visible in the code.
Is the C++ compiler allowed to replace each of the following two codes with an empty code (something that does nothing)? Similarly, are these optimizations allowed to happen at runtime?
I am just trying to get a better understanding of how things work.
num.fetch_add(1,std::memory_order_relaxed);
num.fetch_sub(1,std::memory_order_relaxed);
and
num.fetch_add(1,std::memory_order_relaxed);
std::this_thread::yield();
num.fetch_sub(1,std::memory_order_relaxed);
回答1:
I think in theory yes and even yield
does not help.
But in practice no not today but possible in the future.
See:
- N4455 No Sane Compiler Would Optimize Atomics
- P0062R1: When should compilers optimize atomics?
"Runtime optimization" may happen if modifications coalesce. I don't know if this situation may happen in practice or not. Anyway it is not much distinguishable from "no other threads manage to observe modified value before it changes back"
In fact, the optimization effect is equivalent to "no other threads manage to observe modified value before it changes back", no matter if it is compiler optimization, or runtime. Yield is not guaranteed to help, at least because it just "gives opportunity to reschedule", which an implementation might decide to ignore. And in theory there's no synchronization between yield
and an atomic operation.
On the other hand what do you expect to achieve with this?
来源:https://stackoverflow.com/questions/61604389/are-these-allowed-optimizations-in-c