问题描述
据我所知,编译器优化从未被声明为可变挥发性
。不过,我宣布一个这样的数组。
挥发性多头排列; [8]
和不同的线程读取和写入。的数组的元素仅由一个线程修改和任何其他线程读取。然而,在某些情况下,我已经注意到,即使我从一个线程修改元素,该线程读取它没有注意到的变化。它使在阅读同样的老值,则编译器缓存的地方吧。但是编译器校长不应该缓存volatile变量,对不对?那么怎么来这种情况正在发生。
注意:我不使用挥发性
线程同步,所以请别再给我解答,如使用锁定或原子变量。我知道挥发,原子变量和互斥之间的差异。另外请注意,该架构的x86其中有主动缓存一致性。我也看了变量足够长的时间后,它被认为可以通过其他线程修改。即使经过很长一段时间,读线程不能看到修改后的值。
No, the compiler in principle must read/write the address of the variable each time you read/write the variable.
[Edit: At least, it must do so up to the point at which the the implementation believes that the value at that address is "observable". As Dietmar points out in his answer, an implementation might declare that normal memory "cannot be observed". This would come as a surprise to people using debuggers, mprotect
, or other stuff outside the scope of the standard, but it could conform in principle.]
In C++03, which does not consider threads at all, it is up to the implementation to define what "accessing the address" means when running in a thread. Details like this are called the "memory model". Pthreads, for example, allows per-thread caching of the whole of memory, including volatile variables. IIRC, MSVC provides a guarantee that volatile variables of suitable size are atomic, and it will avoid caching (rather, it will flush as far as a single coherent cache for all cores). The reason it provides that guarantee is because it's reasonably cheap to do so on Intel -- Windows only really cares about Intel-based architectures, whereas Posix concerns itself with more exotic stuff.
C++11 defines a memory model for threading, and it says that this is a data race (i.e. that volatile
does not ensure that a read in one thread is sequenced relative to a write in another thread). Two accesses can be sequenced in a particular order, sequenced in unspecified order (the standard might say "indeterminate order", I can't remember), or not sequenced at all. Not sequenced at all is bad -- if either of two unsequenced accesses is a write then behavior is undefined.
The key here is the implied "and then" in "I modify an element from a thread AND THEN the thread reading it does not notice the change". You're assuming that the operations are sequenced, but they're not. As far as the reading thread is concerned, unless you use some kind of synchronization the write in the other thread hasn't necessarily happened yet. And actually it's worse than that -- you might think from what I just wrote that it's only the order of operations that is unspecified, but actually the behavior of a program with a data race is undefined.
这篇关于可以编译器有时缓存变量声明为volatile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!