Tom*_*bes 5 c++ optimization const volatile
我想优化一些C++代码.让我们举一个简化的例子:
int DoSomeStuff(const char* data)
{
while(data != NULL)
{
//compute something and use optimization as much as possible
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我知道*data
其他地方没有改变.我的意思是它没有在任何其他线程中更改,但编译器无法知道.有没有办法告诉编译器指针上的数据在范围的整个生命周期内都没有改变?
更新:
int DoSomeStuff(const volatile char* data)
{
while(data != NULL)
{
//compiler should assume that the data are changed elsewhere
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
根据标准(7.1.6.1):
A pointer or reference to a cv-qualified type need not actually point or refer
to a cv-qualified object, but it is treated as if it does
Run Code Online (Sandbox Code Playgroud)
所以我将其理解为:编译器将优化对const限定变量的所有访问,就好像它确实是 const 数据并且无法通过非 const 变量的路径进行修改。
根据标准(1.10):
The execution of a program contains a data race if it contains two conflicting
actions in different threads, at least one of which is not atomic, and neither
happens before the other. Any such data race results in undefined behavior.
Run Code Online (Sandbox Code Playgroud)
冲突行为定义为:
Two expression evaluations conflict if one of them modifies a memory location
(1.7) and the other one accesses or modifies the same memory location.
Run Code Online (Sandbox Code Playgroud)
发生之前的关系很复杂,但据我了解,除非您在代码中显式使用原子操作(或互斥体),否则从两个线程(一个写入,另一个读取/写入)访问同一变量是未定义的行为。这种情况是未定义的行为,我认为编译器不会保护你,并且可以自由优化。
Volatile 旨在防止优化 (7.1.6.1):
volatile is a hint to the implementation to avoid aggressive optimization
involving the object because the value of the object might be changed by means
undetectable by an implementation
Run Code Online (Sandbox Code Playgroud)
考虑一下内存映射的 I/O 寄存器(如特殊的输入端口)。即使您无法写入它(因为您的硬件实现是只读的),您也无法优化读取访问(因为它们每次都会返回不同的字节)。例如,这个特殊的 I/O 端口可以是温度传感器。
归档时间: |
|
查看次数: |
327 次 |
最近记录: |