Are these allowed optimizations in C++? [duplicate]

纵然是瞬间 提交于 2021-02-11 05:09:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!