中是允许的优化吗

中是允许的优化吗

本文介绍了这些在 C++ 中是允许的优化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::atomic;num{0}; 被定义在代码中可访问/可见的地方.C++ 编译器是否允许将以下两个代码中的每一个替换为空代码(什么都不做)?同样,这些优化是否允许在运行时发生?我只是想更好地了解事物的运作方式.

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);

num.fetch_add(1,std::memory_order_relaxed);
std::this_thread::yield();
num.fetch_sub(1,std::memory_order_relaxed);

推荐答案

我认为理论上是的,即使 yield 也无济于事.

I think in theory yes and even yield does not help.

但在实践中不是今天,而是可能在未来.

But in practice not today but possible in the future.

见:

如果修改合并,可能会发生运行时优化".我不知道这种情况在实践中是否会发生.无论如何,它与没有其他线程在它变回之前设法观察修改后的值"没有太大区别

"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"

实际上,优化效果就相当于没有其他线程在它变回之前设法观察到修改后的值",无论是编译器优化,还是运行时.Yield 不能保证有帮助,至少因为它只是提供了重新安排的机会",而实现可能会决定忽略这一点.理论上,yield 和原子操作之间没有同步.

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?

这篇关于这些在 C++ 中是允许的优化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:25